【问题标题】:How to use Coalesce for string concatenation in a subquery?如何在子查询中使用 Coalesce 进行字符串连接?
【发布时间】:2011-04-12 02:46:03
【问题描述】:

我正在尝试使用“Coalesce”将一个表中的多个行值串连起来,用逗号分隔并将其列为子查询中的一列。

类似的东西

Declare @assignTo nvarchar(4000)

Select 
table1.columnA
table1.columnB
(
select @assignTo = Coalesce(@assignTo + ', ', '') + CAST(Name as nvarchar(250))
from
table2    
where
...
)
from table1
where

.....

我不断收到“'=' 附近的语法错误。”

如果我只是尝试执行调用 Coalesce 函数的子查询,那很好。即

 Declare @assignTo nvarchar(4000) 
 select @assignTo = Coalesce(@assignTo + ', ', '') + CAST(Name as nvarchar(250))
    from
    table2    
    where
    ...
  Select @assignTo

没关系。所以我的问题是,我如何将它作为子查询包含在内?

非常感谢

ps:这是特定于 SQL Server 2000 的。

【问题讨论】:

    标签: sql subquery concatenation sql-server-2000 coalesce


    【解决方案1】:

    不能将其作为子查询包含:您必须将其移动到 UDF 中。

    在 SQL Server 2005 中,您可以使用 XML PATH 技术。但是对于 SQL Server 2000,您必须有一个单独的标量 UDF,具有表访问和连接功能

    【讨论】:

    • 感谢 gbn。就像我怀疑的那样……哦,好吧,是时候升级数据库了。再次感谢
    【解决方案2】:

    据我所知, 如果您喜欢作为子查询,您可以这样做。 但是上面的解决方案是最方便的。

    Declare @assignTo nvarchar(4000)
    
    Select 
    table1.columnA
    table1.columnB
    tmp.[c]
    from table1,
         (
          select @assignTo = Coalesce(@assignTo + ', ', '') + CAST(Name as nvarchar(250)) as [c]
          from
          table2    
          where
          ...
          ) as tmp
    where
    

    希望它有效!

    【讨论】:

      猜你喜欢
      • 2020-07-01
      • 1970-01-01
      • 2011-05-07
      • 1970-01-01
      • 2023-03-02
      • 2011-04-25
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多