SQL游标使用——格式、实例、嵌套

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/yiyelanxin/article/details/72675703

在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,...
    END
CLOSE 游标名称
DEALLOCATE 游标名称 (释放游标)

二、具体实例:

declare @id int
declare @name varchar(50)
declare cursor1 cursor for         --定义游标cursor1
select * 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  --将游标向下移行
end
close cursor1                   --关闭游标
deallocate 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_test
as
declare @id int,@tags varchar(50),@add_time datetime
declare cursor1 cursor for
select top(10) SupplyID,Keywords,AddDate from SupplyInfo order by supplyid desc
open cursor1
fetch next from cursor1 into @id,@tags,@add_time
while @@fetch_status=0
begin
    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_time
end
close cursor1
deallocate cursor1 

猜你喜欢

转载自blog.csdn.net/yiyelanxin/article/details/72675703