在SQL Server中执行条件连接

时间:2014-09-23 16:41:45

标签: sql-server

我有一个SQL Server数据库。我的数据库有两个表:

Customer             Order
--------             -----
ID (int)             ID (int)
Name                 CustomerID (int)
EmailAddress         

当我查询这些表时,我可能有一个orderID。如果我有订单ID,我想退回与之相关的客户。如果我没有订单ID,或者它等于0,我想要退回所有客户。为了做到这一点,我写了以下查询:

SELECT 
  o.[ID]
FROM
  [Order] o
WHERE 
  o.[ID]=@orderID

此查询返回包含OrderID的所有订单。但是,我不确定如何进行条件查询。这在SQL Server中甚至可能吗?如果是这样,怎么样?

3 个答案:

答案 0 :(得分:0)

您可以使用sql server中的COALESCE来实现它 -

SELECT c.*
FROM customer c
WHERE c.Id IN (
        SELECT o.[CustomerID]
        FROM [Order] o
        WHERE o.[ID] = COALESCE(@orderID, o.[ID])
        )

答案 1 :(得分:0)

我可以想到几种方法:

SELECT * 
FROM Customer
WHERE CustomerID = coalsece( (select TOP 1 customerID from Orders WHERE OrderId= @OrderID), CustomerID)

With CustomerOrders As (
     SELECT CustomerID, ID as OrderID
     FROM Orders
     WHERE OrderID = @OrderID
)
SELECT DISTINCT c.*
FROM Customer c
INNER JOIN CustomerOrders co ON c.ID = coalesce(co.CustomerID, c.ID)

答案 2 :(得分:0)

对于您想要的内容,您可以使用带有Conduit答案的case语句。基本上

CASE
  WHEN @orderid = 0 OR @orderid IS NULL
    SELECT * from Customer
  ELSE
    select c.*
    from Customer c
      inner join order o
        on c.ID = o.CustomerID
    where o.orderID = @orderID
END;

可能不准确,我不在安装了Sql Server的盒子上。