如何在WHILE EXISTS()循环中分配变量

时间:2017-05-17 07:40:13

标签: tsql

我想遍历满足特定条件的表行。在每次迭代中,我想将当前行的两个值分配给变量。这是我到目前为止所得到的:

    WHILE EXISTS(SELECT TOP 1 *
FROM [Communications] c
WHERE [communicationTypeID] = 2
AND [status] = 0)

SET @communicationId = c.[id]
SET @message = c.[Message]
BEGIN
....

显示错误:

Msg 4104, Level 16, State 1, Line 25
The multi-part identifier "c.id" could not be bound.
Msg 4104, Level 16, State 1, Line 26
The multi-part identifier "c.Message" could not be bound.

有人可以指引我指向正确的方向吗?我对SQL很新。 先感谢您。 彼得

1 个答案:

答案 0 :(得分:2)

看起来应该是这样:(小心点,不要运行无限循环...在循环中的内容中正确更新通信,或者在你的东西之后删除id)

WHILE EXISTS(SELECT TOP 1 *
    FROM [Communications] c
    WHERE [communicationTypeID] = 2
    AND [status] = 0)


BEGIN

SET @communicationId = (SELECT TOP 1 [id] FROM [Communications] WHERE [communicationTypeID] = 2 AND [status] = 0)
SET @message = (SELECT [Message] FROM [Communications] WHERE [id] = @communicationId )

/*Do your stuff here*/

DELETE FROM [Communications] WHERE [id] = @communicationId -- only if you need to delete...

END

或者您可以使用光标:

DECLARE ExampleCursor CURSOR FOR
    SELECT [id], [Message]
        FROM [Communications] c
        WHERE [communicationTypeID] = 2
              AND [status] = 0

OPEN ExampleCursor
FETCH NEXT FROM ExampleCursor INTO @communicationId,@message

WHILE @@FETCH_STATUS = 0
BEGIN

/*do your stuff here by using @communicationId and @message for example*/ 
INSERT INTO NextTable (addParams)
SELECT addParams
FROM [Communications]
WHERE id = @communicationId

END


CLOSE ExampleCursor;
DEALLOCATE ExampleCursor;