假设我正在处理10张图书证,每张卡都有客户价值(例如会员编号,会员姓名......),我需要更新每张卡的价值。
如果我想从数据库中抓取所有十个但只想一次更新一行,是否有替代游标?我知道while循环可能有效但是每次循环时我怎么能抓住一行直到我完成所有10张卡?
答案 0 :(得分:9)
不需要使用游标。我大部分时间都在使用它:
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
答案 1 :(得分:0)
可以使用特定列上的聚簇索引在表上循环。因为聚簇索引按排序顺序排列行,所以它可以像循环的索引变量一样使用。
declare @uid int
select @uid = 0 -- assume the uids in table are > 0
declare @rowsaf int
select @rowsaf = 1
while @rowsaf > 1
begin
set rowcount 1
select @uid = uid from customers where uid > @uid
select @rowsaf = @@rowcount
-- update the row using @uid
end
set rowcount 0
Here is the article详细解释了这一点。