2017-05-17 7 views
1

特定の条件が満たされているテーブル行を繰​​り返し処理したいと思います。各繰り返しで、現在の行の値の2つを変数に代入したいと思います。これは私がこれまでに得たものである:WHILE EXISTS()ループで変数を割り当てる方法

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を初めて熟知しています。 ありがとうございます。 ピーター

+0

使用FAST_FORWARDカーソルおよび@@ FETCH_STATUSまでフェッチ:カーソルを使用= 0(記事の良い例B.) – vitalygolub

答えて

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 

またはすることができます代わりにhttps://docs.microsoft.com/en-us/sql/t-sql/language-elements/declare-cursor-transact-sql

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; 
+0

@Matejさん、ありがとうございました。私の問題を解決しました。 –

関連する問題