2

我有一个关于 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

4 回答 4

7

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

DECLARE @out as varchar(max)

SET @Out = ''

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

SELECT @out

看这里

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

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

(1 row(s) affected)
于 2012-04-19T20:08:44.880 回答
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!
于 2012-04-19T20:02:03.440 回答
0

SELECT [User] + ' 说:' + [Observation] FROM [TableName]

于 2012-04-19T20:02:37.813 回答
0
SELECT User +' says: ' + Observation AS USER_SAID
FROM TABLE;
于 2012-04-19T20:02:49.290 回答