从SELECT结果创建varchar

时间:2011-06-15 13:36:21

标签: sql sql-server tsql sql-server-2008

DECLARE @result varchar(MAX)

SELECT 
  NAME
FROM
  Table
WHERE
  ID = @Id

我需要在@result中填入结果名称,用','分隔 例如,如果SELECT返回“A”,“B”和“C”,则@result应为“A,B,C”。
它是Microsoft SQL Server 2008。

4 个答案:

答案 0 :(得分:9)

DECLARE @result varchar(MAX)
SET @result = '';

SELECT 
  @result = @result + NAME + ','
FROM
  Table
WHERE
  ID = @Id

SET @result = SUBSTRING(@result, 1, LEN(@result) - 1)

SELECT @result

享受:D

答案 1 :(得分:1)

DECLARE @CSV varchar(max)

SET @CSV = ''

SELECT @CSV = @CSV + Col1 + ',' FROM Table WHERE ...

SET @CSV = LEFT(@CSV, LEN(@CSV) -1)

PRINT @CSV

答案 2 :(得分:0)

试试这个

declare @result varchar(max)

select @result = COALESCE(@result + ', ', '') + name
from table

答案 3 :(得分:0)

DECLARE @Contribution AS VARCHAR(MAX) SET @Contribution = ( SELECT RTRIM(Ltrim(C.strname))+'; “ 来自tbl M. INNER JOIN tbl2 ON tbl2.ID = tbl.CID 在哪里M.PID = @ PID ORDER BY C.Orderby FOR XML PATH('') )

打印@Contribution