Concat field value to string in SQL Server

后端 未结 6 1032
北荒
北荒 2020-11-27 07:40

I need a similar function to Oracle WM_CONCAT in SQL Server, which returns a comma separated list of whatever field you pass it as argument. For example, in Ora

相关标签:
6条回答
  • 2020-11-27 08:23

    In SQL Server 2017 STRING_AGG function has been added

    SELECT t.name as TableName
          ,STRING_AGG(c.name, ';') AS FieldList
      FROM sys.tables t
      JOIN sys.columns c 
        ON t.object_id = c.object_id
      GROUP BY t.name;
    
    0 讨论(0)
  • 2020-11-27 08:27

    try this

     select    
        wm_concat(name) 
     from
        employee
     where
        state='CA'
     group by
        state
    
    0 讨论(0)
  • 2020-11-27 08:28

    Try this:

    
        drop table #mike_temp 
    go
    
    select * into #mike_temp 
      from (select 'Ken'  as firstname, 'CO' as state
             union all
            select 'Mike' as firstname, 'CO' as state
             union all
            select 'Tom' as firstname , 'WY' as state
           ) a
    go
    
    SELECT distinct 
           state
          ,STUFF((SELECT ', ' + b.firstname FROM #mike_temp b where a.state = b.state FOR XML PATH('')),1, 2, '') AS CSVColumn
      from #mike_temp a
    
    0 讨论(0)
  • 2020-11-27 08:29

    The actual answer:

    SELECT
       SUBSTRING(buzz, 2, 2000000000)
    FROM
        (
        SELECT 
            firstname
        FROM 
            employee
        WHERE
            State = 'CA'
        FOR XML PATH (',')
        ) fizz(buzz)
    

    A common question here. Some searches:

    • FOR XML PATH

    • concat rows csv [sql-server]

    0 讨论(0)
  • 2020-11-27 08:36

    AFAIK, you need to do it by yourself.

    You could build an user defined function that loop with a cursor the records of Employee where the state is CA and returns the concatenation of their names.

    0 讨论(0)
  • 2020-11-27 08:41
     SELECT Field1, Substring(Field2, 2, LEN(Field2)) AS Field2 FROM
    (
        SELECT
            [InnerData].Field1,
            (SELECT  ',' + Field2 FROM @Fields WHERE Field1=[InnerData].Field1 FOR XML PATH('')) AS Field2
            FROM
            (
                SELECT DISTINCT Field1 FROM @Fields
            ) AS [InnerData]
    ) AS OuterData
    

    I got this Query from this Link

    Refer this Link for more Clarification

    0 讨论(0)
提交回复
热议问题