【问题标题】:Why SQL Server Ignores vaules in string concatenation when ORDER BY clause specified为什么 SQL Server 在指定 ORDER BY 子句时忽略字符串连接中的值
【发布时间】:2011-07-29 03:12:42
【问题描述】:

我有下表

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

我需要将所有 cmets 收集到单个字符串中

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

如果没有订购,它会按预期工作,最终返回所有这些 cmets。 但是在运行添加了 ORDER BY 子句的以下代码后:

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

只返回最后一条评论。 有谁知道为什么 ORDER BY 会导致连接中的奇怪结果?

PS:如果使用 FOR XML 子句而不是串联Is there a way to create a SQL Server function to “join” multiple rows from a subquery into a single delimited field?,它可以正常工作。

【问题讨论】:

    标签: sql sql-server sql-order-by concatenation


    【解决方案1】:

    因为您依赖于未记录的行为。

    微软说“The correct behavior for an aggregate concatenation query is undefined.”。如果计算标量移动到计划中的错误位置,那么它就会停止工作!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-22
      • 2013-10-15
      • 1970-01-01
      • 1970-01-01
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多