假设我正在处理10张借书卡,每张卡都有客户价值(例如:会员编号、会员名称...)我需要为每张卡更新一个值。
如果我想从数据库中获取全部10个数据,但每次只更新一行,那么有没有替代游标的方法呢?我知道while循环可能会起作用,但我如何能够在每次循环时都抓取一行,直到我处理完所有10张牌?
发布于 2012-03-03 04:43:12
不需要使用游标。我大部分时间都在用这个:
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发布于 2013-05-26 00:45:59
可以使用特定列上的聚集索引对表进行循环。因为聚集索引按排序顺序排列行,所以它可以像循环的索引变量一样使用。
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 0Here is the article详细解释了这一点。
https://stackoverflow.com/questions/9539918
复制相似问题