sql游标学习资料.docxSQL游标学习
游标一般格式:
DECLARE 游标名称 CURSOR FOR SELECT 字段 1,字段 2,字段 3,... FROM 表 名 WHERE...
OPEN游标名称
FETCH NEXT FROM 游标名称INTO变量名1,变量名2,变量名3,...
WHILE @***@FETCH_STATUS=0
BEGIN
SQL语句执行过程......
FETCH NEXT FROM游标名称INTO变量名1,变量名2,变量名 3,...
END
CLOSE游标名称
DEALLOCATE游标名称
例子:
/*
功能:数据库表格tbl_users数据
deptid userid username
1 100 a
101 b
102 c
要求用一个sql语句输出下面结果
deptid username
ab
c
[要求用游标实现]
设计:OK_008
时间:2006-05
备注:无
*/
create table #Templ(deptid int,userid int,username varchar(20))"待测试的数据表
create table #Temp2(deptid int,username varchar(20)) -■结果表
-■先把一些待测试的数据插入到待测试表#Templ中
insert into #Temp 1
select 1,100,'a' union all
select 1,101/b* union all
select 1,131,'d* union all
select 1,201,'f union all
select 2,302,'c' union all
select 2,202,'a' union all
select 2,221,'e' union all
select 3,102,'y' union all select 3,302,'e' union all select 3,121/t' declare ***@deptid int,***@usemame varchar(20)
-定义游标
declare Select_cursor cursor for
select deptid,username from #Templ
open Select_cursor
fetch next from Select_cursor into ***@deptid,***@username ■■提取操作的列数据放到
局部变量中
while @***@fetch_status=O --返回被FETCH语句执行的最后游标的状态
/*
@***@FETCH_STATUS =0 FETCH 语句成功
@***@FETCH_STATUS=-1 FETCH语句失败或此行不在结果集中
@***@FETCH_STATUS=-2被提取的行不存在
*/
begin
--当表#Temp2列deptid存在相同的数据时,就直接在列username 上追加***@usemame值
if(exists(select * from #Temp2 where deptid=***@deptid ))
update #Temp2 set usemame=usemame +***@username where
deptid=@ deptid
else
-插入新数据
insert into #Temp2 select @ deptid, ©username
fetch next from Select_cursor into @ deptid, ***@username
end
close Select_cursor
deallocate Select_cursor
select * from #Temp2 --测试结果
Drop table #Temp 1 ,#Temp2
自动生成表的更新数据的存储过程
设计原因:在数据库设计中,有时候建立了很多表,每个表都有Insert、Update> Delete结构基本相同的存储,要是能有个自动生成表的更新数据的存储过程,就 方便了我们不必浪费时间去写每一张表的Insert、Update、Delete存储过程。
设计方法:先提取表的各字段信息,包含字段的数据类型、数据定义长度、是否 主键等。再根据提取出来的信息构造成表的更新数据的存储过程。下面的方法是 有一个用户自定义函数FN_GetObjCollnfo和一个存储过程SP_CreateProcdure来 实现。
用户自定义函数FN_GetObjColInfo: 功能:返回某一表的所有字段、存储过程、函数的参数信息 设计:OK_008 时间:2006-05 */
sql游标学习资料 来自淘豆网m.daumloan.com转载请标明出处.