如何创建T-SQL语句字符串以更新表

时间:2017-02-13 18:03:45

标签: sql-server tsql

我需要创建一个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语句外,一切正常。

1 个答案:

答案 0 :(得分:0)

从您的查询

' WHERE Id = ' + CAST(@contadorMensagens AS VARCHAR(1))

您要多次更新同一行。 @contadorMensagens也应与@dataPesquisa@currentDayCount一起更新。因此,满足条件Id = ' + CAST(@contadorMensagens AS VARCHAR(1))的行只会在#AnaliseDeErros417中更新。该行还将包含仅来自while循环的最后一次迭代的值。如果AnaliseDeErros417中没有这样的行,则不会更新任何行。