3

我有一个查询

WHILE @@fetch_status = 0 
BEGIN   
   SET @message =' ,' + CASE WHEN @year < 10 THEN 'socyr0' ELSE 'socyr' END + CAST(@year AS varchar) + ' as '+ CAST(@sql AS varchar) + ','  
   PRINT @message   
   FETCH NEXT FROM SocioCursor INTO @year
   SET @sql = @sql + 1 
END

结果是几个字符串

socyr08 as 2006,  
socyr09 as 2007,  
socyr10 as 2008,  
socyr11 as 2009,  
socyr12 as 2010,  

我应该改变什么才能得到

socyr08 as 2006,  
socyr09 as 2007,  
socyr10 as 2008,  
socyr11 as 2009,  
socyr12 as 2010  
4

2 回答 2

4

我不确定您是否期望它们出现在一行文本中。我认为你可以在没有光标的情况下像下面那样做。

如果您需要没有换行符的单行,请根据需要调整variable length right function删除。char(13)

Sql-Fiddle 演示

declare @sql int = 2006, @message varchar(500)

select @message = isnull(@message + ',' + char(13), '') + 
                  'socyr' + right(100 + year, 2) + ' as ' + 
                  convert(varchar(4), @sql), 
                  @sql = @sql +1
from T

select @message


| COLUMN_0     |
----------------
socyr01 as 2006,
socyr02 as 2007,
socyr09 as 2008,
socyr10 as 2009,
socyr11 as 2010 
于 2013-04-03T10:53:43.893 回答
1

您需要在循环@message创建和打印变量。

在循环中,您只需向其中添加一个片段,如下所示:@message = @message + ...

然后,打印之前,您需要修剪最后一个逗号字符:

@message = SUBSTRING ( @message, 1, LEN (@message) - 1 )
于 2013-04-03T10:49:58.743 回答