日期:2014-05-19  浏览次数:20410 次

如何在存储过程中使用循环语句一条一条地对符合条件的结果进行操作
在一个存储过程中对一张表进行更新
SELECT   a_name,a_num   FROM   tb_a   WHERE   a_num> 20
要对符合这个查询条件的记录UPDATE,但由于权限问题,只能通过一个已有的SP:sp_tba_update   进行更新,而sp_tba_update接收参数   @a_name  
内容大致为:update   tb_a   set     a_num=a_num-10   WHERE   a_name=@a_name  
我需要在SELECT的时候取出   a_name   然后如果有记录循环调用sp_tba_update
请问这个SP该怎么写?

------解决方案--------------------

declare @a_name varchar(20)
declare cur_tmp cursor for
select a_name from tb_a where a_num> 20
open cur_tmp
fetch next from cur_tmp into @a_name
while @@fetch_status=0
begin
exec sp_tba_update @a_name
fetch next from cur_tmp into @a_name
end
close cur_tmp
deallocate cur_tmp
------解决方案--------------------
数据量不大时,可以这样:
declare @sql varchar(8000)
set @sql= ' '
select @sql=@sql+char(10)+ 'update tb_a set a_num=a_num-10 where a_name= '+quotename(a_name)
from tb_a where a_num> 20

exec(@sql)
------解决方案--------------------
没有update权限可能不行.