Using COALESCE in SQL view

前端 未结 2 1916
生来不讨喜
生来不讨喜 2021-02-06 03:02

I need to create a view from several tables. One of the columns in the view will have to be composed out of a number of rows from one of the table as a string with comma-separat

2条回答
  •  执念已碎
    2021-02-06 03:12

    In SQL Server 2008, you can take advantage of some of the features added for XML to do this all in one query without using a stored proc:

     SELECT CustomerName,
        STUFF( -- "STUFF" deletes the leading ', '
            ( SELECT ', ' + OrderName
            FROM Orders
            WHERE CustomerId = Customers.CutomerId
            -- This causes the sub-select to be returned as a concatenated string
            FOR XML PATH('') 
            ),
        1, 2, '' )
        AS Orders
     FROM Customers
    

提交回复
热议问题