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

假装没事ソ 提交于 2019-12-29 08:09:08

问题


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], 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?.


回答1:


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!



来源:https://stackoverflow.com/questions/5538187/why-sql-server-ignores-vaules-in-string-concatenation-when-order-by-clause-speci

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!