从光标返回一个表

时间:2013-05-09 09:19:30

标签: sql sql-server tsql sql-server-2005

请参阅以下代码:

    DECLARE @ID int
DECLARE @errorflag int

DECLARE Warning_Cursor CURSOR FOR
    SELECT TOP 3 ID FROM Warnings
    SET @errorflag = @errorflag + @@Error  
    OPEN Warning_cursor
        SET @errorflag = @errorflag + @@Error  
        FETCH NEXT FROM Warning_cursor INTO @ID
        WHILE @@FETCH_STATUS = 0  
    begin
        SELECT @ID
        FETCH NEXT FROM Warning_cursor INTO @ID
    END
CLOSE Warning_cursor
DEALLOCATE Warning_cursor

游标返回三个表,每个表一行。如何返回一个包含三行的表?

2 个答案:

答案 0 :(得分:1)

你为什么不这样做,

SELECT TOP 3 ID FROM Warnings

更一般地说,如果你使用光标,你可能做错了。


如果由于某种原因而不必使用游标,则该游标不属于问题。你可以做到

DECLARE @Id int;
DECLARE @Ids TABLE (Id Int);
DECLARE Warning_Cursor CURSOR FOR SELECT TOP 3 ID FROM Warnings;
OPEN Warning_cursor; 
FETCH NEXT FROM Warning_cursor INTO @Id;
WHILE @@FETCH_STATUS = 0 BEGIN
    INSERT @Ids SELECT @Id;

    FETCH NEXT FROM Warning_cursor INTO @Id;
END
CLOSE Warning_cursor;
DEALLOCATE Warning_cursor;
SELECT Id FROM @Ids;

答案 1 :(得分:0)

答案是创建一个临时表,如下所示:

   DECLARE @ID int
DECLARE @errorflag int
DECLARE @CONCATRESULT TABLE (ID INT)
DECLARE Warning_Cursor CURSOR FOR
    SELECT TOP 3 ID FROM Warnings
    SET @errorflag = @errorflag + @@Error  
    OPEN Warning_cursor
        SET @errorflag = @errorflag + @@Error  
        FETCH NEXT FROM Warning_cursor INTO @ID
        WHILE @@FETCH_STATUS = 0  
    begin
        INSERT into @CONCATRESULT (ID) VALUES (@ID)
        FETCH NEXT FROM Warning_cursor INTO @ID
    END
CLOSE Warning_cursor
DEALLOCATE Warning_cursor
select id from @CONCATRESULT