2009-11-23 164 views
5

我在這個sql-server查詢中使用IF語句時遇到問題。sql-server,SQL查詢中的IF語句

我想要什麼:

如果salesHeader.[Ship-to Name]不爲空,我需要返回,作爲DeliveryName,如果爲空,否則返回的東西。

有沒有辦法在查詢中使用if語句來做到這一點?

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

回答

9

或者使用COALESCE ...

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

COALESCE將返回列表中的第一個非NULL值

11

的使用情況,不IF

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

編輯:

兩者結合並ISNULL答案給在其他的答案是同樣有效過這種特殊情況下(和更簡單的,坦率地說)

1

不確定,但是您是否必須將'AS DeliveryName'以外的作爲IF?

至少,它是如何工作在MySQL的

5

你可以使用CASE:

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

或者在這種情況下您可以使用COALESCE或ISNULL:

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

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