要求:不用游标,不修改表格式(没有自增长字段),怎么遍历表?
------解决方案--------------------
如果是2005及以上的版本,可以用下面的代码:
--drop table test
create table test(id int,v varchar(100))
insert into test
select 10,'abc' union all
select 11,'abc' union all
select 12,'abc' union all
select 20,'abc' union all
select 2,'abc' union all
select 3,'abc' union all
select 4,'abc' union all
select 5,'abcd' union all
select 6,'abcf' union all
select 7,'abca' union all
select 8,'abce' union all
select 9,'abcd'
go
declare @i int
set @i = 1;
while @i <= (select COUNT(*) from test)
begin
;with t
as
(
select *,
ROW_NUMBER() over(order by @@servername) as rownum
from test
)
select * from t where rownum = @i;
set @i = @i + 1;
end
/*
id v rownum
----------- ---------------------------------------------------------------------------------------------------- --------------------
10 abc 1
(1 行受影响)
id v rownum
----------- ---------------------------------------------------------------------------------------------------- --------------------
11 abc 2
(1 行受影响)
id v rownum
----------- ---------------------------------------------------------------------------------------------------- --------------------
12 abc 3
(1 行受影响)
id v rownum