在SQL中实现for循环以更新行

时间:2019-03-25 21:30:28

标签: sql sql-server tsql sql-server-2008

如何用SQL编写以下代码?该查询将从结果中更新表中的每一列。

DECLARE @table_list NVARCHAR -- What data type do I use to hold a list?
DECLARE @column_list NVARCHAR

SET @table_list = (SELECT DISTINCT [ID_TABLE_NAME] FROM dbo.VMO) -- there are more than one results 
SET @column_list = (SELECT DISTINCT [USR_COL_NAME] FROM dbo.VMO) -- there are more than one results 

foreach(@table IN @table_list)
{
    foreach(@column IN @column_list)
    {
        UPDATE @table
        SET @column = '101211'
        WHERE @column = '10120'
    }
}

2 个答案:

答案 0 :(得分:1)

您可以使用CURSOR充当foreach循环:

code

答案 1 :(得分:-1)

T-SQL没有FOR loop,也许有WHILE (Transact-SQL)

使用如下所示的SQL:

DECLARE @table_list NVARCHAR -- What data type do I use to hold a list?
DECLARE @column_list NVARCHAR

SET @table_list = (SELECT DISTINCT [ID_TABLE_NAME] FROM dbo.VMO) -- there are more than one results 
SET @column_list = (SELECT DISTINCT [USR_COL_NAME] FROM dbo.VMO) -- there are more than one results 

WHILE @column_list > @table_list
BEGIN
  UPDATE @table
        SET @column = '101211'
        WHERE @column = '10120'
END;