views:

207

answers:

5

I have the following query, that makes up a View.

I'm having trouble with the IF statement within it. Basically, if salesHeader.[Ship-to Name] isn't null, i need to return that AS DeliveryName, if it is null, return something else.

There are several fields like this (i've only included one for now)

Is there a way of doing this?

SELECT
   poHeader.No_ AS PONumber, 
   poHeader.[Buy-from Vendor No_] AS VendorNumber, 
   poHeader.[Document Date] AS DocDate, 
   salesHeader.GiftMessage, 
   salesHeader.[Delivery Comment] AS DeliveryComment,                     
   salesHeader.[Shipment Date] AS DeliveryDate, 
   IF salesHeader.[Ship-to Name] IS NOT NULL 
      salesHeader.[Ship-to Name] AS DeliveryName
   ELSE
      poHeader.[Ship-to Name] AS DeliveryName
   END 
FROM         
    dbo.[Crocus Live$Purch_ orders for e-mailing] AS poForEmailing 
LEFT OUTER JOIN
    dbo.[Crocus Live$Purchase Header] AS poHeader ON poForEmailing.No_ = poHeader.No_ 
INNER JOIN
    dbo.[Crocus Live$Vendor] AS vendor ON poHeader.[Buy-from Vendor No_] = vendor.No_ 
LEFT OUTER JOIN
    dbo.[Crocus Live$Sales Header] AS salesHeader ON salesHeader.No_ = dbo.fnGetSalesOrderNumber(poHeader.No_)
+6  A: 

Use CASE, not IF

CASE 
    WHEN salesHeader.[Ship-to Name] IS NOT NULL THEN salesHeader.[Ship-to Name]
    ELSE poHeader.[Ship-to Name]
END AS DeliveryName

Edit:

Both COALESCE and ISNULL answers give in other answers are equally valid too for this particular case (and simpler, frankly)

gbn
A: 

Not sure, but don't you have to put the 'AS DeliveryName' outside the IF?

At least that's how it works in MySQL...

Seb
+5  A: 

Or use COALESCE...

SELECT 
COALESCE(salesHeader.[Ship-to Name], poHeader.[Ship-to Name]) AS DeliveryName

COALESCE will return the first non-NULL value in the list

lJohnson
+2  A: 

You can use CASE:

(CASE WHEN cond-1 THEN value-if-1
      WHEN cond-2 THEN value-if-2
      ELSE default-value END) AS column-name

Or in this situation you can use COALESCE or ISNULL:

COALESCE(salesHeader.[Ship-to Name], poHeader.[Ship-to Name]) AS DeliveryName

ISNULL(salesHeader.[Ship-to Name], poHeader.[Ship-to Name]) AS DeliveryName
Tomek Szpakowicz
+1  A: 

As what gbn said, use CASE statement instead.

Since he has already done the coding, so I don't want to place the same thing again.

Instead just giving you some site to refer for your understanding

a) SQL SERVER – CASE Statement/Expression Examples and Explanation

b) CASE function in SQL Server 2005 - part I

c) CASE function in SQL Server 2005 - part II

d) CASE Function in SQL Server 2005 - part III

priyanka.sarkar