假设我正在处理10张图书证,每张卡都有客户价值(例如会员编号,会员姓名......),我需要更新每张卡的价值.
如果我想从数据库中获取所有十个但只想一次更新一行,是否有替代游标?我知道while循环可能有效但是每次循环时我怎么能抓住一行直到我完成所有10张卡?
不需要使用游标.我大部分时间都在用这个:
declare @uid int -- this is the type unique index on the table you're updating
-- Copy out the unique ids of the rows you want to update to a temporary table
select uid into #temp from customers -- you can use a where condition here
-- Loop through the rows of the temp table
while exists (select 1 from #temp)
begin
set rowcount 1
select @uid = uid from #temp -- pull one uid from the temp table
set rowcount 0
delete from #temp where uid = @uid -- delete that uid from the temp table
-- Do something with the uid you have
update customers set name = 'Joe Shmoe' where uid = @uid
end
Run Code Online (Sandbox Code Playgroud)