Using COALESCE in SQL view

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

提交回复
热议问题