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_)
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)
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With