如何将循环sp_executesql输出连接到变量中

时间:2015-08-29 17:22:03

标签: tsql string-concatenation sp-executesql

我使用下面的过程,我试图将返回的itemstr连接到变量strlist,并在值之间使用逗号。我在每个外观迭代中获得单独的itemstr值,但strlist始终为null。

   alter procedure my_test

   as 

   declare @counter int
   declare @columnstr varchar(100)
   declare @itemstr varchar(100)
   declare @strlist varchar(1000)

   declare @sqlstr nvarchar(1000)

   set @counter = 1


   while @counter < 15
   begin
     set @columnstr = 'txt_item' + ltrim(cast(@counter as varchar(2)))
     --select @columnstr as columnstr

     set @sqlstr = 'select @outstr = ' + @columnstr + ' from group1_ where id = ''298'''
     --select @sqlstr

   execute sp_executesql @sqlstr,N'@outstr varchar(100) OUTPUT',   @outstr=@itemstr OUTPUT;
   select @itemstr as itemstr

    set @strlist = @strlist + @itemstr + ','
    select @strlist as strlist  -- this is always null

    set @counter = @counter + 1
   end
   select @strlist     -- this is always null
   go

1 个答案:

答案 0 :(得分:1)

尝试确保字符串在创建时不为空

要么

 declare @strlist varchar(1000) = ''

OR

set @strlist = ISNULL(@strlist,'') + @itemstr + ','