5

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_)

5 Answers 5

11

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)

Sign up to request clarification or add additional context in comments.

Comments

10

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

Comments

5

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

Comments

2

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

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.