2012-06-18 68 views
2

有沒有人知道如何爲同一個光標設置不同的select語句?我需要這樣的想法。如何通過某些條件更改遊標的select語句?

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 

....等

我已經找到解決方案: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

+2

或者你可以使用動態SQL ... –

+0

我同意@MitchWheat +1。這也減少了代碼行。 – Pankaj

+0

謝謝你的接觸。我在這裏找到了一些很好的解決方案http://blog.sqlauthority.com/2007/01/01/sql-server-simple-example-of-cursor/ – Radislav

回答

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

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 '