文档详情

《SQL数据库资料整理2016》.doc

发布:2015-10-16约1.89万字共21页下载文档
文本预览下载声明
发表地址:/viewthread.php?action=printabletid=127814 前言:最近比较忙,一直没时间整理自己的帖子和文件,这里整理的,主要是一些工作中碰到、朋友问到的已经解决了的资料;代码的例子多,说明的文字部分少点!,^-^,文采不好,就是有点懒,大多代码;有些资料可能会重复、存在在错误,希望大家能提出与谅解。 作者:DVD/OK_008 整理时间:2006-12联系方式:glal@163.com my blog: / SQL游标学习WHILE @@FETCH_STATUS=0 BEGIN SQL语句执行过程... ... FETCH NEXT FROM 游标名称 INTO 变量名1,变量名2,变量名3,... END CLOSE 游标名称 DEALLOCATE 游标名称 例子: /* 功能:数据库表格tbl_users数据 deptid userid username 1 00 a 1 101 b 2 102 c 要求用一个sql语句输出下面结果 deptid username1 ab 2 c [要求用游标实现] 设计: OK_008 时间: 2006-05 备注:无 */ insert into #Temp1 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,@username varchar(20) --定义游标 declare Select_cursor cursor for select deptid,username from #Temp1 open Select_cursor fetch next from Select_cursor into @deptid,@username --提取操作的列数据放到局部变量中 while @@fetch_status=0 --返回被 FETCH 语句执行的最后游标的状态 /* @@FETCH_STATUS =0 FETCH 语句成功 @@FETCH_STATUS =-1 FETCH 语句失败或此行不在结果集中 @@FETCH_STATUS =-2 被提取的行不存在 */ begin --当表#Temp2列deptid存在相同的数据时,就直接在列username上追加@username值 if(exists(select * from #Temp2 where deptid=@deptid )) update #Temp2 set username=username +@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 #Temp1,#Temp2 自动生成表的更新数据的存储过程 设计原因:在数据库设计中,有时候建立了很多表,每个表都有Insert、Update、Delete结构基本相同的存储,要是能有个自动生成表的更新数据的存储过程,就方便了我们不必浪费时间去写每一张表的Insert、Update、Delete存储过程。 设计方法:先提取表的各字段信息,包含字段的数据类型、数据定义长度、是否主键等。再根据提取出来的信息构造成表的更新数据的存储过程。下面的方法是有一个用户自定义函数FN_GetObjColInfo和一个存储过程SP_CreateProcdure来实现。 用户自定义函数FN_GetObjColInfo: /* 功能:返回某一表的所有字段、存储过程、函数的参数信息 设计:OK_008 时间:2006-05
显示全部
相似文档