sql-server,SQL Query中的IF语句

时间:2009-11-23 15:23:13

标签: sql sql-server tsql

我在此sql-server查询中使用IF语句时遇到问题。

我想要的是什么:

如果salesHeader.[Ship-to Name]不为null,我需要返回AS DeliveryName,如果为null,则返回其他内容。

有没有办法在查询中使用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_)

5 个答案:

答案 0 :(得分:11)

使用CASE,而不是IF

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

编辑:

COALESCE和ISNULL答案给出的其他答案对于这个特殊情况同样有效(并且更简单,坦率地说)

答案 1 :(得分:9)

或使用COALESCE ......

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

COALESCE将返回列表中的第一个非NULL值

答案 2 :(得分: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

答案 3 :(得分:2)

正如gbn所说,请改用CASE语句。

由于他已经完成了编码,所以我不想再重复同样的事情了。

而只是给你一些网站来引用你的理解

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

答案 4 :(得分:1)

不确定,但是你不必把'AS DeliveryName'放在之外吗?

至少这是它在MySQL中的运作方式......