我需要创建一个T-SQL语句字符串来更新while循环中的表。
WHILE @currentDayCount <= @amountOfDays
BEGIN
SELECT @totalErros = COUNT(*)
FROM ErrorLog
WHERE StatusCode = 417
AND Response LIKE '%' + @mensagemResponse + '%'
AND CAST(CreationDate AS DATE) = CAST(@dataPesquisa AS DATE)
SET @SQL = 'UPDATE #AnaliseDeErros417 SET ' +
CAST(FORMAT(CAST(@dataPesquisa AS DATE), 'dd/MM') AS VARCHAR(10)) +
' = ' + CAST(@totalErros AS VARCHAR(8)) + ' WHERE Id = ' + CAST(@contadorMensagens AS VARCHAR(1));
EXECUTE(@SQL)
SET @dataPesquisa = DateADD(DAY, 1, @dataPesquisa)
SET @currentDayCount = @currentDayCount + 1;
END
除了更新SQL语句外,一切正常。
答案 0 :(得分:0)
从您的查询
' WHERE Id = ' + CAST(@contadorMensagens AS VARCHAR(1))
您要多次更新同一行。 @contadorMensagens
也应与@dataPesquisa
和@currentDayCount
一起更新。因此,满足条件Id = ' + CAST(@contadorMensagens AS VARCHAR(1))
的行只会在#AnaliseDeErros417
中更新。该行还将包含仅来自while循环的最后一次迭代的值。如果AnaliseDeErros417
中没有这样的行,则不会更新任何行。