将两行作为单行返回

时间:2014-03-31 16:11:10

标签: sql sql-server

请参阅下面的SQL DDL:

create table dbo.Test(id int, name varchar(30))

INSERT INTO Test values (1, 'Mark') 
INSERT INTO Test values (2,'Williams')

我想回归:' Mark Williams'使用SQL SELECT。我尝试过使用SQL Pivot,但它没有用。

3 个答案:

答案 0 :(得分:1)

试试这个:

DECLARE @Return VARCHAR(MAX)

SELECT @Return = COALESCE(@Return+' ','') + name
FROM dbo.TEST

SELECT @Return

答案 1 :(得分:1)

DECLARE @NameList VARCHAR(8000) 
SELECT @NameList = COALESCE(@NameList + ' ', '') + Name 
FROM Test
SELECT @NameList 

了解更多COALESCE

答案 2 :(得分:1)

可能比COALESCE更灵活地使用STUFF和FOR XML模式:

SELECT TOP 1
       STUFF((SELECT ' ' + Name AS [text()]
                FROM dbo.Test 
               ORDER BY id
                 FOR XML PATH('')), 1, 1, '' ) Concatenated
 FROM TEST