I'm working with Dynamic SQL (still in the learning phase) and I'm stuck at a part where I need to use a WHILE loop:
SET @tableName = (SELECT DISTINCT TableName FROM @dataStructure)
Here basically I want to make sure that the operations inside the while loop should occur for all the tables in the @tableName (defined above). I don't know how I can give this condition as an input for the while loop.
WHILE() #HOW CAN I PUT THE CONDITION HERE????
BEGIN
SET @str = ''
SET @sqlstr = ''
SELECT @table = TableName FROM @dataStructure
SET @str = 'UPDATE a0' + char(13) + char(10)
+ ' SET a0.Mjolnir_Source_ID = CONCAT( '
SELECT @str = @str + IIF(ReferenceTable IS NULL, 'a0.' + columnName , alias + '.Mjolnir_Source_ID') + ','
FROM @dataStructure
WHERE TableName = @tableName AND ReferenceTable IS NOT NULL
ORDER BY columnName
SELECT @str = @str + ') FROM ' + @table + ' a0'
SELECT @sqlstr = @sqlstr + +
+ ' INNER JOIN ' + QUOTENAME(@U4SM_db_name) + '.dbo.' + QUOTENAME(ReferenceTable) + ' ' + alias + char(13) + char(10)
+ ' ON a0.' + columnName + ' = ' + alias + '.' + ReferenceColumn + char(13) + char(10)
FROM @dataStructure
WHERE TableName = @tableName AND ReferenceTable IS NOT NULL
ORDER BY columnPosition
select @str + @sqlstr
select @sqlstr
SET @tableName = @tableName + 1
END
Can anyone please help me out here?
WHILEand would use string aggregation. What are you trying to achieve here against each table?