SQL Server 2005數據庫游標調用函數實例解析
SQL Server 2005數據庫游標調用函數的使用是本文我們主要要介紹的內容,本文我們通過一個具體的實例來介紹這一過程,接下來我們就開始介紹。
1、建立基表
- create table planwork
- (
- planid int,
- empid int
- )
- insert into planwork values (1,100)
- insert into planwork values (2,200)
- insert into planwork values (3,300)
- insert into planwork values (4,400)
- insert into planwork values (5,500)
- insert into planwork values (6,600)
- insert into planwork values (7,700)
- insert into planwork values (8,800)
- select * fom planwork
2、建立函數
- drop function findworkplan
- create function findworkplan(@num int)
- returns int
- as
- begin
- declare @eid int
- set @eid=(select empid from planwork where planid=@num)
- return @eid;
- end;
3、測試函數
- select dbo.findworkplan(3)
4、利用游標調用函數
4.1、創建一個表,利用這個表里面的數值得到workplan表里面對應的empno
- create table xb_test1
- (
- xid int
- )
- insert into xb_test1 values (1)
- insert into xb_test1 values (2)
- insert into xb_test1 values (3)
- insert into xb_test1 values (4)
- insert into xb_test1 values (5)
- insert into xb_test1 values (6)
- insert into xb_test1 values (7)
- insert into xb_test1 values (8)
- select * from xb_test1
4.2、只能用循環遍歷xb_test1表 分別找出對應表workplan的empno,考慮到需遍歷整個xb_test1表, 所以決定用游標,不知道用oracle的with函數怎么樣?該 WHILE 結構測試用于游標的函數 @@FETCH_STATUS 的返回值。因為 @@FETCH_STATUS 可能返回 –2、-1 或 0,所以,所有的情況都應進行測試。如果某一行在開始執行此存儲過程以后從游標結果中刪除,將跳過該行。成功提取 (0) 后將執行 BEGIN...END 循環內部的 SELECT 語句。
- declare empno_cursor cursor
- for
- select xid from xb_test1
- open empno_cursor
- declare
- @a int,
- @result int
- fetch next from empno_cursor into @a
- while (@@fetch_status <> -1)
- begin
- if (@@fetch_status <> -2)
- begin
- --print @a
- set @result=(select dbo.findworkplan(@a))
- print @result
- end
- fetch next from empno_cursor into @a
- end
- close empno_cursor
- deallocate empno_cursor
關于SQL Server 2005數據庫游標調用函數的使用就介紹到這里了,希望本次的介紹能夠對您有所收獲!
【編輯推薦】