I am attempting to use a WHILE loop with dynamic SQL. See code below.
I have a table [Users] that set out various conditions required to update fields in [DB1] with a Status Code. The code runs, however [DB1] only has updated records based on last row in the USERS table which suggests it is not looping through the dynamic SQL variables.
Would anyone be able to advise how to iterate over the [Users] table?
Please note I have coded this using a SQL Cursor solution, however attempting to use WHILE loop. Thanks.
DECLARE @Field VARCHAR(50)
DECLARE @FieldType VARCHAR(10)
DECLARE @Operator CHAR(5)
DECLARE @Value VARCHAR(50)
DECLARE @Status VARCHAR(10)
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
DECLARE @Count INT = 1
DECLARE @RowCount INT
SET @RowCount = (SELECT COUNT(1) FROM [DB1])
DECLARE @SQL VARCHAR(MAX)
WHILE @Count<=@RowCount
BEGIN
SELECT @Field = [Field]
,@FieldType= [FieldType]
,@Operator=[Operator]
,@Value=[Value]
,@Status=[Status]
,@StartDate=CONVERT(VARCHAR(11),[StartDate],106)
,@EndDate=CONVERT(VARCHAR(11),[EndDate],106)
FROM [USERS] (NOLOCK)
ORDER BY [ConfigOrder] ASC
SET @SQL= 'UPDATE [DB1]
SET [Status] = ''' + @Status + '''' +
'FROM [DB1] AS a (NOLOCK)
INNER JOIN [DB2] AS b (NOLOCK) ON a.ID = b.ID
WHERE b.[status] = ''UNK''
AND ' + @Field + '' + @Operator + '' + @Value +
'AND a.[start_date] >= ''' + CONVERT(VARCHAR(11),@StartDate,106) + '''' +
'AND a.[start_date] <= ''' + CONVERT(VARCHAR(11),@EndDate,106) + '''' ;
EXEC (@SQL)
SET @Count=@Count+1
END
SELECT @Field = [Field] ,@FieldType= [FieldType] ,@Operator=[Operator] ,@Value=[Value] ,@Status=[Status] ,@StartDate=CONVERT(VARCHAR(11),[StartDate],106) ,@EndDate=CONVERT(VARCHAR(11),[EndDate],106) FROM [USERS] (NOLOCK) ORDER BY [ConfigOrder] ASCadvance inside the loop?NOLOCKhint? What do you think it does against the table you areUPDATEing? How do youUPDATEa table while ignoring other locks?