SQL Server 2005數(shù)據(jù)庫游標(biāo)調(diào)用函數(shù)實例解析
作者:獨孤島
本文我們主要介紹了SQL Server 2005數(shù)據(jù)庫中游標(biāo)調(diào)用函數(shù)的使用實例,通過這個實例,讓我們一起來了解一下游標(biāo)調(diào)用函數(shù)的使用吧,希望能夠?qū)δ兴鶐椭?/div>
SQL Server 2005數(shù)據(jù)庫游標(biāo)調(diào)用函數(shù)的使用是本文我們主要要介紹的內(nèi)容,本文我們通過一個具體的實例來介紹這一過程,接下來我們就開始介紹。
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、建立函數(shù)
- 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、測試函數(shù)
- select dbo.findworkplan(3)
4、利用游標(biāo)調(diào)用函數(shù)
4.1、創(chuàng)建一個表,利用這個表里面的數(shù)值得到workplan表里面對應(yīng)的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、只能用循環(huán)遍歷xb_test1表 分別找出對應(yīng)表workplan的empno,考慮到需遍歷整個xb_test1表, 所以決定用游標(biāo),不知道用oracle的with函數(shù)怎么樣?該 WHILE 結(jié)構(gòu)測試用于游標(biāo)的函數(shù) @@FETCH_STATUS 的返回值。因為 @@FETCH_STATUS 可能返回 –2、-1 或 0,所以,所有的情況都應(yīng)進行測試。如果某一行在開始執(zhí)行此存儲過程以后從游標(biāo)結(jié)果中刪除,將跳過該行。成功提取 (0) 后將執(zhí)行 BEGIN...END 循環(huán)內(nèi)部的 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
關(guān)于SQL Server 2005數(shù)據(jù)庫游標(biāo)調(diào)用函數(shù)的使用就介紹到這里了,希望本次的介紹能夠?qū)δ兴斋@!
【編輯推薦】
責(zé)任編輯:趙鵬
來源:
博客園


相關(guān)推薦




