2012-09-25 90 views
2

我必須根據可以爲空的值來選擇連接列來連接。 詳細:SQL服務器條件連接

SELECT shoporders.orderid, 
    shopaddresses.companyname, 
    shopaddresses.firstname, 
    shopaddresses.lastname, 
    shopaddresses.address1, 
FROM shoporders 
    INNER JOIN shopaddresses 
      ON shoporders.InvoiceAddressId = shopaddresses.addressid 
where orderid = 110 
order by shoporders.createddate desc 

如果shoporders.InvoiceAddressId爲null,則我不得不使用shoporders.DeliveryAddressId

任何線索?

在此先感謝

回答

6
ON coalesce(shoporders.InvoiceAddressId, shoporders.DeliveryAddressId) = shopaddresses.addressid 
3

你可以嘗試

SELECT shoporders.orderid, 
    shopaddresses.companyname, 
    shopaddresses.firstname, 
    shopaddresses.lastname, 
    shopaddresses.address1, 
FROM shoporders 
    INNER JOIN shopaddresses 
      ON COALESCE (shoporders.InvoiceAddressId, shoporders.DeliveryAddressId) = shopaddresses.addressid 
where orderid = 110 
order by shoporders.createddate desc 

編輯:對於聚結的定義,見MSDN。總結如下

返回其參數中的第一個非空表達式。 COALESCE(expression1,...n)等同於以下CASE表達:

CASE 

    WHEN (expression1 IS NOT NULL) THEN expression1 

    WHEN (expression2 IS NOT NULL) THEN expression2 

    ... 

    ELSE expressionN 

END 
0

您可以嘗試

SELECT shoporders.orderid, 
     shopaddresses.companyname, 
     shopaddresses.firstname, 
     shopaddresses.lastname, 
     shopaddresses.address1, 
     FROM shoporders 
     INNER JOIN shopaddresses 
     ON( 
      (shoporders.InvoiceAddressId IS NOT NULL 
        AND shoporders.InvoiceAddressId = shopaddresses.addressid) 
      OR (shoporders.DeliveryAddressId = shopaddresses.addressid) 
     ) 

     WHERE orderid = 110 
     ORDER BY shoporders.createddate DESC