2

有没有人知道如何为同一个游标设置不同的选择语句?我需要这样的想法。

DECLARE Temp_Cursor CURSOR FOR
IF(@TempVar = 1)
BEGIN
    SELECT CustomerId FROM Customers
END
ELSE IF(@TempVar = 2)
BEGIN
    SELECT OrderId FROM Orders
END
OPEN Temp_Cursor;
FETCH NEXT FROM TempCursor INTO @TempObjectId
WHILE @@FETCH_STATUS = 0
BEGIN 

.... ETC

我找到了解决方案:DECLARE @Temp_Cursor CURSOR IF(@TempVar = 1) BEGIN SET @Temp_Cursor = CURSOR FOR SELECT CustomerId FROM Customers END ELSE IF(@TempVar = 2) BEGIN SET @Temp_Cursor = CURSOR FOR SELECT OrderId FROM Orders END OPEN @Temp_Cursor; FETCH NEXT FROM @TempCursor INTO @TempObjectId WHILE @@FETCH_STATUS = 0 BEGIN

4

2 回答 2

1

完整的查询应该是动态的。这意味着执行计划将在运行时出现。

例子

Declare @SelectStatement Varchar(50)
Declare @SQL Varchar(50)

IF(@TempVar = 1)
BEGIN
    Set @SelectStatement = SELECT CustomerId FROM Customers
END
ELSE IF(@TempVar = 2)
BEGIN
    Set @SelectStatement = SELECT OrderId FROM Orders
END

Set @SQL = 'DECLARE Temp_Cursor CURSOR FOR
OPEN Temp_Cursor;
FETCH NEXT FROM TempCursor INTO ' + @TempObjectId +
'WHILE @@FETCH_STATUS = 0
BEGIN '
于 2012-06-18T09:53:34.680 回答
1

放在IF外面,做两个不同的游标,每种情况一个。

像这样:

IF(@TempVar = 1)
BEGIN

    DECLARE Temp_Cursor CURSOR FOR
    SELECT CustomerId FROM Customers


    OPEN Temp_Cursor;
    FETCH NEXT FROM TempCursor INTO @TempObjectId
    WHILE @@FETCH_STATUS = 0
    BEGIN 
    ....
END
ELSE IF(@TempVar = 2)
BEGIN

    DECLARE Temp_Cursor CURSOR FOR
    SELECT OrderId FROM Orders


    OPEN Temp_Cursor;
    FETCH NEXT FROM TempCursor INTO @TempObjectId
    WHILE @@FETCH_STATUS = 0
    BEGIN 
    ....
END

另一种可能性是使用Dynamic SQL

于 2012-06-18T09:54:08.737 回答