您的位置:首页 > 数据库

SQL中用游标循环更新数据(原)

2011-10-04 22:47 417 查看
在实际项目中,有时候会用到数据得更新,我最近就遇到了。我有一个产品表(product),其中有三个字段是外键对象的ID,可是现在需要做搜索了,所以存ID就不行了,要在产品的关键字里面存储这三个外键ID的Name属性,也就是要存储对象的名称而不是ID,这样便于抓取数据(本人使用的Lucene,对纯文本抓取比较强悍)。

那么现在问题很清楚了,就是要逐条更行产品表里面的每一条记录。我的关键字的定义规格是:“产品名称,第一类型名称,第二类型名称,第三类型名称”。也就是说,需要对每一行进行这样一个操作:首页根据三个外键ID查询出对应的Name名称,然后把三个Name和产品名称根据规则连在一起,再更新这条数据的关键字列。

好了,那思路很清楚了,做一件事,然后循环就可以了,那就要先做这件事,也就是创建一个存储过程,来完成第一步。

View Code 1 use 数据库名称
2 go
3 if exists(select * from sysobjects where name = 'updateKeyword')
4 drop procedure updateKeyword
5 go
6 create proc updateKeyword
7 @productID varchar(50)
8
9 as
declare @typeID varchar(50)
declare @typeID2 varchar(50)
declare @typeID3 varchar(50)
declare @typeName varchar(50)
declare @typeName2 varchar(50)
declare @typeName3 varchar(50)
if exists (select * from manager_product where ID = @productID)
begin
select @typeID = productFirstType_ID,@typeID2 = productSecondType_ID,@typeID3 = productThirdType_ID
from manager_product where ID = @productID
print 'typeIDs show : '+@typeID+','+@typeID2+','+@typeID3
end

if(@typeID is null)
begin
select @typeName = ''
end
else
begin
if exists (select * from manager_producttype where ID = @typeID)
begin
select @typeName = typeName from manager_producttype where ID = @typeID
print 'cunzai typeID : ' + @typeID +',typeName :'+ @typeName
end

end

if(@typeID2 is null)
begin
select @typeName2 = ''
end
else
begin
if exists (select * from manager_producttype where ID = @typeID2)
begin
select @typeName2 = typeName from manager_producttype where ID = @typeID2
print 'cunzai typeID2 : ' + @typeID2 +',typeName2 :'+ @typeName2
end
end

if(@typeID3 is null)
begin
select @typeName3 = ''
end
else
begin
if exists (select * from manager_producttype where ID = @typeID3)
begin
select @typeName3 = typeName from manager_producttype where ID = @typeID3
print 'cunzai typeID3 : ' + @typeID3 +',typeName3 :'+ @typeName3
end
end
print 'updateString : '+ @typeName + @typeName2 + @typeName3
update manager_product set productKeyword = productName + ',' + @typeName +','+@typeName2+','+@typeName3
where ID = @productID 好了,第一步经过测试,ok了。基本上完成了需求,可以实现:更新一条产品信息,将其关键字更新成需要的规则了。

现在进行第二步,就是循环这个操作,对产品表的每一条数据进行更新。这里我选用了游标来完成。

1 declare @productID nvarchar(50)
2 declare cursorOfID cursor for
3 select ID from manager_product
4 --打开游标
5 open cursorOfID
6 --获取数据,游标下移一行
7 fetch next from cursorOfID into @productID
8 --检测获取数据是否成功
9 while @@fetch_status=0
begin
--显示通过游标赋值的变量
exec updateKeyword @productID --执行
--游标继续下移
fetch next from cursorOfID into @productID
end
--关闭游标
close cursorOfID 在第12行,调用了写好的存储过程来完成更新,每次更新完,让游标往下读一行,将新值赋给@productID,这样就实现了循环更新数据了。

测试,通过。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: