Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Tsql 如何在WHILE EXISTS()循环中分配变量_Tsql - Fatal编程技术网

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

Tsql 如何在WHILE EXISTS()循环中分配变量,tsql,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, Lev

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

    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很陌生。 先谢谢你。 Peter

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

或者您可以使用光标:

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;

改为使用快进游标,直到@@fetch\u STATUS=0为止(本文中的好例子B)
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;