sql server 游标的运用
昨天由于要对数据库中大片没有插入的数据进行修复,因此想到了遍历每条数据和修改遍历的数据。
由于并没有有序的字段,不能简单的用while循环,因此,需要用到游标。
下面对sql 语句进行分析。
begin
declare @pid varchar(50)
declare @path varchar(260)
declare @date varchar(50)
declare @rpath varchar(260)//前4行是声明的变量
declare order_cursor cursor
for(select[Patient_ID]from [HisReport1].[dbo].[His_report] where report_Date between ‘2017-01-05’ and ‘2017-01-06’)//第五、六行用于声明一个游标,并指明游标作用范围
open order_cursor//打开一个游标
fetch next from order_cursor into @pid //将查到结果的第一个值赋给变量pid
while @@FETCH_STATUS=0//开始进行循环,判断fetch的状态
begin
select @date=exam_date from [zhilikangDrPacs].[dbo].[dicom_baseInfo] where patient_id=@pid
set @rpath=’\192.168.0.25\ImageData2’+STUFF(stuff(@date,7,2,’’),5,0,’-’)+’’+STUFF(@date,1,6,’’)+’’+@pid+’’
update [HisReport1].[dbo].[His_report] set image_path=@rpath where Patient_ID=@pid
fetch next from order_cursor into @pid
end//begin 和and 之间是你想要处理的语句
close order_cursor//关闭游标
deallocate order_cursor//释放游标
end
go
这里再说一下stuff函数,stuff(param1,param2,param3,param4);
参数1是要处理的字符串,可以是常量也可以是变量
参数2表明要处理字段的开始位置
参数3表明从要处理字段的开始位置处理多长字节
参数4表示修改方法,删除就写‘’,替换就写要替换的东西
来源:CSDN
作者:weixin_42834523
链接:https://blog.csdn.net/weixin_42834523/article/details/103868568