我今天在SQL Server(2008R2和2012)中遇到了一个非常奇怪的问题.我正在尝试使用串联和select语句来构建字符串.
我找到了解决方法,但我真的很想了解这里发生了什么以及为什么它没有给我预期的结果.有人可以向我解释一下吗?
http://sqlfiddle.com/#!6/7438a/1
根据要求,这里的代码也是:
-- base table
create table bla (
[id] int identity(1,1) primary key,
[priority] int,
[msg] nvarchar(max),
[autofix] bit
)
-- table without primary key on id column
create table bla2 (
[id] int identity(1,1),
[priority] int,
[msg] nvarchar(max),
[autofix] bit
)
-- table with nvarchar(1000) instead of max
create table bla3 (
[id] int identity(1,1) primary key,
[priority] int,
[msg] nvarchar(1000),
[autofix] bit
)
-- fill the three tables with the same values …Run Code Online (Sandbox Code Playgroud) 我有下表
Created Comment
2010/10/10 Text1
2010/11/11 Text2
2010/12/12 Text3
Run Code Online (Sandbox Code Playgroud)
我需要将所有注释收集到单个字符串中
SELECT @Comment = COALESCE(@Comment, '')
+ CHAR(13) + CHAR(10) + CONVERT(NVARCHAR(30), [dbo].[Comment].[Created], 101) + ': ' + ISNULL([Comment].[Text], '')
FROM Comment
Run Code Online (Sandbox Code Playgroud)
没有订购它按预期结束工作返回所有评论.但在运行以下代码后,添加了ORDER BY子句:
SELECT @Comment = COALESCE(@Comment, '')
+ CHAR(13) + CHAR(10) + CONVERT(NVARCHAR(30), [Created], 101) + ': ' + ISNULL([Text], '')
FROM Comment
ORDER BY Created
Run Code Online (Sandbox Code Playgroud)
只返回最后一条评论.有没有人知道为什么ORDER BY导致串联中的奇怪结果?
PS:如果使用FOR XML子句而不是连接,它可以正常工作是否有办法创建SQL Server函数以将子查询中的多行"连接"到单个分隔字段?.