SQL SERVER 拼字串方式 動態表名 遊標變數範例
儲存過程1:
CREATE PROCEDURE [dbo].[pro_get_cursor]
@In_TableName nvarchar(200),
@Out_CurrencyCursor CURSOR VARYING OUTPUT
AS
declare @sql nvarchar(2000)
set @sql=N'DECLARE CurrencyCursor CURSOR
FORWARD_ONLY STATIC FOR
SELECT * FROM '+@In_TableName
EXEC(@sql)
OPEN CurrencyCursor;
SET @Out_CurrencyCursor = CurrencyCursor;
儲存過程2:(呼叫儲存過程1)
CREATE PROCEDURE [dbo].[pro_test_c]
AS
BEGIN
DECLARE @MyCursor CURSOR;
declare @str1 varchar(100)
declare @str2 varchar(100)
declare @str3 varchar(100)
declare @str4 nvarchar(100)
declare @str5 nvarchar(100)
declare @i int=1
EXEC dbo.pro_get_cursor '表名',@Out_CurrencyCursor = @MyCursor OUTPUT;
FETCH NEXT FROM @MyCursor into @str1,@str2,@str3,@str4,@str5
WHILE (@@FETCH_STATUS = 0)
BEGIN;
print convert(nvarchar(5),@i)
set @i= @i+1
FETCH NEXT FROM @MyCursor into @str1,@str2,@str3,@str4,@str5
END;
CLOSE @MyCursor;
DEALLOCATE @MyCursor
--注意此處: 呼叫儲存過程1的遊標的不能再次CLOSE,只能催毀對像。否則異常發生。
--CLOSE CurrencyCursor
DEALLOCATE CurrencyCursor
--以下程式碼可以用來檢視遊標的列表
--DECLARE @Report CURSOR
-- Execute sp_cursor_list into the cursor variable.
--EXEC master.dbo.sp_cursor_list @cursor_return = @Report OUTPUT,
-- @cursor_scope = 3
---- Fetch all the rows from the sp_cursor_list output cursor.
--FETCH NEXT from @Report
--WHILE (@@FETCH_STATUS <> -1)
--BEGIN
-- FETCH NEXT from @Report
--END
--CLOSE @Report
--DEALLOCATE @Report
END