需要在单个实例中从sql查询中分配值

时间:2014-05-14 07:23:46

标签: sql sql-server

我在sql-server-2008-R2中执行以下查询,它给出了我想要的输出(即行数)但是,我想以多列的形式存储结果在变量中。

declare @rCount int
declare @kuri nvarchar(max)
declare @IDs nvarchar(max)

select @rCount=10

set @kuri='select top '+cast(@rCount as varchar)+' FLD295,FLD9 from tableName (nolock) ORDER BY NEWID()'

execute(@kuri)

我之前做过这个,但是我需要将查询的结果连接到一列(分配和显示),这是不同的查询

select @IDs=CAST(isnull(@IDs ,'')as varchar)+CAST(COALESCE(fld9,',')as varchar) from table1307 (nolock) ORDER BY NEWID()

3 个答案:

答案 0 :(得分:1)

我认为你错过了你可以做的脸

declare @i int=3

select top(@i) .... –

2008确实支持动态顶级

我希望你知道结果应该是单一的。 ,否则,它是不可能的(除非你正在做insert into...

如果你问的是如何连接(cte是jsut表,请忽略它)

enter image description here

答案 1 :(得分:1)

DECLARE @T1 TABLE (
    FLD9 bigint
, FLD295 nVARCHAR(max)
)

insert into @T1(,FLD295,FLD9) 
select top(@rCount) FLD295,FLD9 from tableName (nolock)
 ORDER BY NEWID()

select * from @T1
select @IDs=CAST(isnull(@IDs ,'')as varchar)+CAST(COALESCE(fld9,',')as varchar) from @T1 

答案 2 :(得分:0)

您可以使用游标访问结果集:

declare @rCount int
declare @kuri nvarchar(max)
declare @IDs nvarchar(max)

declare @FLD295 int
declare @FLD9 int

select @rCount=10

set @kuri='declare cursor curs for select top '+cast(@rCount as varchar)+' FLD295,FLD9 from tableName (nolock) ORDER BY NEWID()'

exec sp_executesql @kuri

open curs
fetch from curs
into @FLD295, @FLD9

while @@fetch_status = 0
BEGIn


fetch from curs
into @FLD295, @FLD9
END

close curs
deallocate curs