Using COALESCE in SQL view

前端 未结 2 1917
生来不讨喜
生来不讨喜 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

    EDIT: Modified answer to include creation of view.

    /* Set up sample data */
    create table Customers (
        CustomerId int,
        CustomerName VARCHAR(100)
    )
    
    create table Orders (
        CustomerId int,
        OrderName VARCHAR(100)
    )
    
    insert into Customers
        (CustomerId, CustomerName)
        select 1, 'John' union all
        select 2, 'Marry'
    
    insert into Orders
        (CustomerId, OrderName)
        select 1, 'New Hat' union all
        select 1, 'New Book' union all
        select 1, 'New Phone'
    go
    
    /* Create the view */       
    create view OrderView as    
        select c.CustomerName, x.OrderNames
            from Customers c
                cross apply (select stuff((select ',' + OrderName from Orders o where o.CustomerId = c.CustomerId for xml path('')),1,1,'') as OrderNames) x
    go
    
    /* Demo the view */
    select * from OrderView
    go 
    
    /* Clean up after demo */
    drop view OrderView
    drop table Customers
    drop table Orders
    go
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题