1

请看下面的代码:

    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

游标返回三个表,每个表有一行。如何返回一张三行表?

4

2 回答 2

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;
于 2013-05-09T09:31:30.953 回答
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 
于 2013-05-09T09:45:21.757 回答