如何在 SQL 服务器中存储值数组并对其进行迭代

How to store array of values in SQL Server and iterate over it

DECLARE @Versions table (id int);

INSERT INTO @Versions
    SELECT DISTINCT Version_Id 
    FROM dbo.values 
    WHERE CatId = (SELECT id FROM dbo.Category WHERE Name = 'Locations') 

SELECT * FROM @Versions --- returns 1,2

到这里为止,我能够获取版本数据并将其存储在 table 值参数版本中。但是现在我需要迭代它来执行一些操作,比如

    WHILE(till @Versions has value )   -- Iterate till @Versions exhausts its value ,which will be ideally 1,2 then stop iteration
     BEGIN 
       -- Update Statements for each version 
     END 

如何指定 运行 直到 @Versions 有值的条件(递增 - 对于版本 1 执行一些更新,然后对 v2 执行相同的操作,然后退出)

另外,如果有更好的方法,请提出建议!

您可以使用 ROW_NUMBER 如下:

;WITH CTE
AS
(
    SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) RowId FROM @Versions
)

DECLARE @Counter INT 
SELECT @Counter = COUNT(*) FROM CTE

WHILE(@Counter != 0)   -- Iterate till @Versions exhausts its value ,which will be ideally 1,2 then stop iteration
    BEGIN 

    -- Current Version
    SELECT * FROM CTE
    WHERE RowId = @Counter

    -- Update Statements for each version 

    SET @Counter -= 1

    END 

或者您可以使用 EXISTS

WHILE(EXISTS(SELECT 1 FROM @Versions))   -- Iterate till @Versions exhausts its value ,which will be ideally 1,2 then stop iteration
 BEGIN 
   -- Update Statements for each version 

   -- After update operation
   DELETE FROM @Versions
   WHERE Id = @CurrentVersionId
 END