Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using COALESCE in SQL view

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-separated values.

Here is a simplified example of what I want to do.

Customers:
CustomerId int
CustomerName VARCHAR(100)

Orders:
CustomerId int
OrderName VARCHAR(100)

There is a one-to-many relationship between Customer and Orders. So given this data

Customers
1 'John'
2 'Marry'

Orders
1 'New Hat'
1 'New Book'
1 'New Phone'

I want a view to be like this:

Name     Orders
'John'   New Hat, New Book, New Phone
'Marry'  NULL

So that EVERYBODY shows up in the table, regardless of whether they have orders or not.

I have a stored procedure that i need to translate to this view, but it seems that you cant declare params and call stored procs within a view. Any suggestions on how to get this query into a view?

CREATE PROCEDURE getCustomerOrders(@customerId int)
AS
   DECLARE @CustomerName varchar(100)
   DECLARE @Orders varchar (5000)

   SELECT @Orders=COALESCE(@Orders,'') + COALESCE(OrderName,'') + ',' 
   FROM Orders WHERE CustomerId=@customerId

   -- this has to be done separately in case orders returns NULL, so no customers are excluded
   SELECT @CustomerName=CustomerName FROM Customers WHERE CustomerId=@customerId

   SELECT @CustomerName as CustomerName, @Orders as Orders
like image 244
kateroh Avatar asked Nov 02 '10 20:11

kateroh


People also ask

Is coalesce better than Isnull?

With ISNULL(), you can only provide one alternate value but with COALESCE you can provide more than one e.g. if col1 IS NULL then take value from column2, if that is NULL then take the default value.

Is coalesce better than case?

COALESCE() is literally shorthand for a CASE statement, they will perform identically. However, as podiluska mentioned, ISNULL() can be occasionally faster than a CASE statement, but it's likely to be a miniscule increase as these functions are very unlikely to bottleneck your procedure.

Is coalesce faster than Isnull?

In a narrow case, using the built-in isnull function results in better performance than coalesce on columns that are not nullable. This pattern should generally be avoided, of course. On columns that are nullable, things can really go sideways in either case.

Can you use coalesce in where clause?

You can use coalesce anywhere, including the where clause, yes.


2 Answers

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
like image 128
Joe Stefanelli Avatar answered Oct 08 '22 00:10

Joe Stefanelli


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
like image 34
David Avatar answered Oct 07 '22 23:10

David