日期:2014-05-17  浏览次数:20627 次

SQL 变量怎么取多行值
declare @su int;
select @su=id from t1;

print @su;


例如这段语句,假如只有一行,自然没有任何问题,但是如果t1表中有多行记录,我如何把每行的ID都取出来赋值给 @su 呢? 谢谢!

------解决方案--------------------
引用:
谢谢指教了,不过稍有一丁点问题,每行取出来的值都是一样的。
declare @su int,@i int,@a int
set @i=1
select @a=count(1) from t1
while @i<@a+1
begin
select @su=id from ( 
select row_number()over(order by id)num,* from t1
)a where num=@i
set @i=@i+1
print @su
end

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


create table t1(id int)

insert into t1
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 5 union all
select 6 union all
select 7 union all
select 8 
go


declare @su int;
declare @count int;   
declare @i int;

--记录条数
set @count = (select count(*) from t1)

set @i = 1;

while @i <= @count
begin
   select @su=id 
   from 
   (select *,row_number() over(order by @@servername) as rownum
    from t1
   )t where rownum = @i
   
   set @i = @i + 1

   print @su;
end;
/*
1
2
3
4
5
6
7
8
*/