我有一个关于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
有办法吗?
答案 0 :(得分: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)
答案 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;
输出:
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;