开发者

Why SQL Server Ignores vaules in string concatenation when ORDER BY clause specified

I have the following table

Created    Comment
2010/10/10 Text1 
2010/11/11 Text2
2010/12/12 Text3

I need gather all comments into the single string

SELECT  @Comment = COALESCE(@Comment, '')
   + CHAR(13) + CHAR(10) + CONVERT(NVARCHAR(30), [dbo].[Comment].[Created], 101) + ': ' + ISNULL([Comment].[Text], '')
    FROM Comment

Without ordering it works as expected end return all thee comments. But after running following code where ORDER BY clause is added:

SELECT  @Comment = COALESCE(@Comment, '')
   + CHAR(13) + CHAR(10) + CONVERT(NVARCHAR(30), [Created],开发者_StackOverflow 101) + ': ' + ISNULL([Text], '')
    FROM Comment
  ORDER BY Created

Return only the last comment. Does any body know why ORDER BY leads to the strange result in concatenation?

PS: It work fine if FOR XML clause used instead of concatenation Is there a way to create a SQL Server function to “join” multiple rows from a subquery into a single delimited field?.


Because you are relying on undocumented behaviour.

Microsoft say "The correct behavior for an aggregate concatenation query is undefined.". If the compute scalar moves to the wrong place in the plan then it just stops working!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜