有沒有人知道如何爲同一個光標設置不同的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
或者你可以使用動態SQL ... –
我同意@MitchWheat +1。這也減少了代碼行。 – Pankaj
謝謝你的接觸。我在這裏找到了一些很好的解決方案http://blog.sqlauthority.com/2007/01/01/sql-server-simple-example-of-cursor/ – Radislav