在SELECT单列ID上循环

时间:2019-03-25 14:56:06

标签: sql-server

我正在尝试根据“单个ID列SELECT查询”的结果获取循环的语法。

我的目标是,每次循环旋转以获取当前的ID号

查询是这样的:

SELECT Id FROM tbl WHERE SomeField = "Something"

让我们说结果是:33,48,76

我想循环显示此结果,以便每次旋转时我都会有一个具有当前数字ID的变量

Start Loop
     @CurrentId = ???
End Loop

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作,使用RDMBS逐行工作不是一个好主意,但是:

DECLARE @id INT;
SELECT TOP 1 @id = id FROM tbl WHERE SomeField = 'Something' ORDER BY id;
WHILE @id IS NOT NULL
BEGIN
    --Do stuff with @id
    DECLARE @old_id INT;
    SELECT @old_id = @id;
    SELECT @id = NULL;
    SELECT TOP 1 @id = id FROM tbl WHERE SomeField = 'Something' AND id > @old_id ORDER BY id;
END;

或者我可能会考虑这样做,因为它在某些方面更清洁:

CREATE TABLE #loop_ids (
    loop_id INT IDENTITY(1,1),
    id INT);
INSERT INTO #loop_ids (id) SELECT id FROM tbl WHERE SomeField = 'Something' ORDER BY id;
DECLARE @id INT;
DECLARE @loop_id INT;
SELECT @loop_id = ISNULL(MAX(id), 0) FROM #loop_ids;
WHILE @loop_id > 0
BEGIN
    SELECT @id = id FROM #loop_ids WHERE loop_id = @loop_id;
    --Do stuff with @id
    SELECT @loop_id = @loop_id - 1; --Or SELECT @loop_id -= 1;
END;