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 
原创粉丝点击