济南建设集团招聘信息网站,利尔化学股票,网站建设进度安排,wd mycloud wordpress在sql语句中#xff0c;如果要实现诸如for循环一样的功能就会用到游标#xff0c;但游标一定要慎用#xff0c;因为使用游标对数据库性能有关很大的影响。
一、游标的一般格式#xff1a;
DECLARE 游标名称 CURSOR FOR SELECT 字段1,字段2,字段3,... FROM 表名 WHERE ...…在sql语句中如果要实现诸如for循环一样的功能就会用到游标但游标一定要慎用因为使用游标对数据库性能有关很大的影响。
一、游标的一般格式
DECLARE 游标名称 CURSOR FOR SELECT 字段1,字段2,字段3,... FROM 表名 WHERE ...
OPEN 游标名称
FETCH NEXT FROM 游标名称 INTO 变量名1,变量名2,变量名3,...
WHILE FETCH_STATUS0BEGINSQL语句执行过程... ...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_status0 --判断是否成功获取数据
beginupdate table1 set namename1where idid --进行相应处理(跟据需要填入SQL文)fetch next from cursor1 into id,name --将游标向下移行
end
close cursor1 --关闭游标
deallocate cursor1 --释放游标
功能说明以select * from table1 的查询结果为基本表即要循环的表在循环到table1的每一行时执行namename’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_status0
beginif (tags is not null) and (tags!)begindeclare value varchar(50)declare cursor2 cursor forselect [Value] from [dbo].[SplitString](tags, ,, 1)open cursor2fetch next from cursor2 into valuewhile fetch_status0begindeclare tag_id int,co intselect cocount(0) from LB_article_tags where titlevalueif co0begininsert into LB_article_tags(title,add_time) values(value,add_time)select tag_idIDENTITYinsert into lb_article_tags_relation(article_id, tag_id) values(id, tag_id)endelse if co0beginselect tag_idid from LB_article_tags where titlevaluedeclare count intselect countcount(0) from lb_article_tags_relation where article_idid and tag_idtag_idif count0insert into lb_article_tags_relation(article_id, tag_id) values(id, tag_id)endfetch next from cursor2 into valueendclose cursor2deallocate cursor2 endfetch next from cursor1 into id,tags,add_time
end
close cursor1
deallocate cursor1