【问题标题】:How to concatenate a string in my case using SQL Server?在我的情况下,如何使用 SQL Server 连接字符串?
【发布时间】:2018-02-14 21:03:26
【问题描述】:

我在一个名为 RelationRecord

的表中有 4 列

关系记录

Parent    Child1    Child2    Child3
------------------------------------
111        111       null      111
222        null      null      null
null       333       null      null
null       null      null      444
555        555       555       555

我想像下面这样用逗号连接和分隔

期待输出

111,111
222
333
444
555,555,555,555

我尝试使用caseisnull,但它不起作用。当我使用案例时,查询会变得很多。有没有替代方案?

【问题讨论】:

    标签: sql sql-server tsql stored-procedures concatenation


    【解决方案1】:

    这是一种方法:

    select stuff( (coalesce(',' + child1, '') +
                   coalesce(',' + child2, '') +
                   coalesce(',' + child3, '') +
                   coalesce(',' + child4, '')
                  ), 1, 1, ''
                 )
    

    stuff() 用于删除结果列中的前导逗号(如果有)。

    【讨论】:

    【解决方案2】:

    如果 2012+,另一个选项是 concat()

    示例

    Select NewValue = IsNull( stuff( concat( ','+Child1
                                            ,','+Child2
                                            ,','+Child3
                                           ),1,1,''),Parent)
     From YourTable
    

    退货

    NewValue
    111,111
    222          -- Notice Parent is displayed
    333
    444
    555,555,555
    

    【讨论】:

      【解决方案3】:

      我并不为此感到自豪,但我做到了

       select 
      isnull(cast(Parent as varchar(19)),'') + 
      case  
          when Parent is null then ''
          when Child1 is null then '' 
          else ',' end + 
      isnull(cast(Child1 as varchar(59)),'')  + 
      case  
          when Child1 is null then ''
          when Child2 is null then '' 
          else ',' end +
      isnull(cast(Child2 as varchar(59)),'') + 
      case  
          when Child2 is null then ''
          when Child3 is null then '' 
          else ',' end +
      isnull(cast(Child3 as varchar(59)),'')from Table_1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-16
        • 2022-07-01
        • 1970-01-01
        • 2021-01-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多