SQL游标使用——格式、实例、嵌套
来源:互联网 发布:win8优化驱动器要几遍 编辑:程序博客网 时间:2024/06/10 07:19
在sql语句中,如果要实现诸如for循环一样的功能就会用到游标,但游标一定要慎用,因为使用游标对数据库性能有关很大的影响。
一、游标的一般格式:
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,... ENDCLOSE 游标名称DEALLOCATE 游标名称 (删除游标)
二、具体实例:
declare @id intdeclare @name varchar(50)declare cursor1 cursor for --定义游标cursor1select * from table1 --使用游标的对象(跟据需要填入select文)open cursor1 --打开游标fetch next from cursor1 into @id,@name --将游标向下移行,获取的数据放入之前定义的变量@id,@name中while @@fetch_status=0 --判断是否成功获取数据begin update table1 set name=name+'1' where id=@id --进行相应处理(跟据需要填入SQL文) fetch next from cursor1 into @id,@name --将游标向下移行endclose cursor1 --关闭游标
功能说明:以select * from table1 的查询结果为基本表,即要循环的表,在循环到table1的每一行时执行name=name+’1’的更新操作。
三、游标嵌套
从表SupplyInfo中查询出标签关键词Keywords(如‘安全柜,工作台,BIOBASE,,’),然后根据’,’进行分割,分割出的单个关键词插入表LB_article_tags,并将SupplyInfo与LB_article_tags的关联关系插入表 lb_article_tags_relation,实现语句如下:
create proc aa_testasdeclare @id int,@tags varchar(50),@add_time datetimedeclare cursor1 cursor forselect top(10) SupplyID,Keywords,AddDate from SupplyInfo order by supplyid descopen cursor1fetch next from cursor1 into @id,@tags,@add_timewhile @@fetch_status=0begin if (@tags is not null) and (@tags!='') begin declare @value varchar(50) declare cursor2 cursor for select [Value] from [dbo].[SplitString](@tags, ',', 1) open cursor2 fetch next from cursor2 into @value while @@fetch_status=0 begin declare @tag_id int,@co int select @co=count(0) from LB_article_tags where title=@value if @co=0 begin insert into LB_article_tags(title,add_time) values(@value,@add_time) select @tag_id=@@IDENTITY insert into lb_article_tags_relation(article_id, tag_id) values(@id, @tag_id) end else if @co>0 begin select @tag_id=id from LB_article_tags where title=@value declare @count int select @count=count(0) from lb_article_tags_relation where article_id=@id and tag_id=@tag_id if @count=0 insert into lb_article_tags_relation(article_id, tag_id) values(@id, @tag_id) end fetch next from cursor2 into @value end close cursor2 deallocate cursor2 end fetch next from cursor1 into @id,@tags,@add_timeendclose cursor1deallocate cursor1
阅读全文
0 0
- SQL游标使用——格式、实例、嵌套
- SQL 嵌套游标的使用
- SQL : 游标使用实例
- SQL游标使用实例
- SQL 游标使用实例
- SQL 游标使用实例
- 游标嵌套游标实例
- SQL游标使用及实例
- SQL游标使用及实例
- SQL游标使用及实例
- 游标嵌套游标的SQL
- 游标嵌套游标的SQL
- sql中嵌套游标
- 存储过程+嵌套游标结合使用的实例
- SQL Server 2008 游标使用实例
- SQL Server 2008 游标使用实例
- SQL游标的使用及实例
- oracle 游标嵌套使用
- 5.24~6.4-Python-语言及其应用-笔记-代码结构
- Android BIN档格式sparse 及 ext4
- 80x86的寻址方式
- 程序员如何快速准备面试中的算法
- ASP.NET Core Kestrel 中使用 HTTPS (SSL)
- SQL游标使用——格式、实例、嵌套
- Spring基础学习教程(spring的常用注解)-02
- Unity调用android7.0以上系统相机崩溃问题
- 程序员面试、算法研究、编程艺术、红黑树、数据挖掘5大系列集锦
- tomcat-users.xml(tomcat 7)配置
- 想在美国找CS软件工作
- 通过tcpdump确认Linux系统是否收到和响应ping包
- Eclipse.自动提示--编写HTML/CSS/JS/JSP代码时自动提示的解决办法
- 扩展KMP