Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql-server, IF statement within SQL Query

I'm having trouble with using an IF statement within this sql-server query.

What I want:

If salesHeader.[Ship-to Name] isn't null, I need to return that AS DeliveryName, if it is null, return something else.

Is there a way to do this with an if statement in a query?

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_)
like image 985
Alex Avatar asked Nov 23 '09 15:11

Alex


4 Answers

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)

like image 74
gbn Avatar answered Nov 01 '22 13:11

gbn


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

like image 22
lJohnson Avatar answered Nov 01 '22 12:11

lJohnson


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
like image 22
Tomek Szpakowicz Avatar answered Nov 01 '22 12:11

Tomek Szpakowicz


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

like image 33
priyanka.sarkar Avatar answered Nov 01 '22 12:11

priyanka.sarkar