在SQL上将行转换为字符串

时间:2012-04-19 19:59:09

标签: sql-server sql-server-2008 sql-server-2008-r2

我有一个关于Sql的表:

ID    User       Observation
========================================
1     John       This is correct!
----------------------------------------
2     Michael    I got an error!
----------------------------------------
3     Joshua     This is incorrect!
----------------------------------------

我想要的是一个函数thar返回一个varchar与字符串上的数据

像这样:

修改 这是我期望的结果:

John says: This is correct!\r\nMichael says: I got an error!\r\nJoshua says: This is incorrect

有办法吗?

4 个答案:

答案 0 :(得分:7)

作为单个列和单行,您可以执行此操作

DECLARE @out as varchar(max)

SET @Out = ''

SELECT @Out = @Out +  [User] + ' says: ' + Observation + CHAR(13) + CHAR(10)  
FROM Table1

SELECT @out

See it here

这是SSMS中的输出(使用文本输出)

-------------------------------
John says: This is correct!
Michael says: I got an error!
Joshua says: This is incorrect!

(1 row(s) affected)

答案 1 :(得分:4)

如果要连接由回车符+换行符分隔的所有行:

declare @UserObservation Table(ID int, [User] varchar(20), Observation varchar(100));
insert into @UserObservation values(1, 'John' ,'This is correct!');
insert into @UserObservation values(2, 'Michael' ,'I got an error!');
insert into @UserObservation values(3, 'Joshua' ,'This is incorrect!');

DECLARE @WhatAllUserSay VARCHAR(8000) ;
SELECT @WhatAllUserSay = 
    COALESCE(@WhatAllUserSay + CHAR(13) + CHAR(10), '') + [User] + ' says: ' + Observation 
FROM @UserObservation

PRINT @WhatAllUserSay;

COALESCE

输出:

John says: This is correct!
Michael says: I got an error!
Joshua says: This is incorrect!

答案 2 :(得分:0)

SELECT [User] +'说:'+ [观察] FROM [TableName]

答案 3 :(得分:0)

SELECT User +' says: ' + Observation AS USER_SAID
FROM TABLE;