如何在子查询中创建具有多个表达式的SQL存储过程

时间:2011-07-22 23:03:07

标签: sql tsql

我有一个Orders表,我想从Orders表中提取一些列,并从两个OrderDetails表中的一个中提取记录,具体取决于Orders表中列的值。

订单

OrderID Pk int
OrderDetails_A_ID
OrderDate
OrderedById

OrderDetails_A

OrderDetails_A_ID Pk int
OrderID Fk int
Qty_A
ItemDesc_A

OrderDetails_B

OrderDetails_B_ID Pk int
OrderID Fk int
Qty_B
ItemDesc_B

这是我所知道的不起作用,但我想做什么。

SELECT O.OrderDate,O.OrderedByID,
CASE WHEN O.OrderDetails_A_ID IS NULL 
     THEN
     SELECT B.ItemDesc_B as ItemDesc,B.Qty_B as Qty
     ELSE
     SELECT A.ItemDesc_A as ItemDesc,A.Qty_A as Qty
     END
FROM Orders as O

3 个答案:

答案 0 :(得分:2)

您的示例中没有包含任何JOIN条件,所以我也会从我的中删除它们。

SELECT O.OrderDate,O.OrderedByID,
CASE WHEN O.OrderDetails_A_ID IS NULL THEN B.ItemDesc_B ELSE A.ItemDesc_A END as ItemDesc,
CASE WHEN O.OrderDetails_A_ID IS NULL THEN B.Qty_B ELSE A.Qty_A END as Qty
FROM Orders as O

答案 1 :(得分:2)

您可以合并或使用带联合的内部联接。

使用coalesce,您可以按字段控制它。使用union,您不必一遍又一遍地指定确切的列。

聚结:

select o.OrderID, COALESCE(a.Qty_A, a.Qty_B) as Qty
from Orders o
left outer join Order_Detail_A a on o.OrderID = a.OrderID and o.OrderDetails_A_ID is not null
left outer join Order_Detail_B b on o.OrderID = b.OrderID and o.OrderDetails_A_ID is null

联盟:

select o.OrderID, a.Qty_A as Qty
from Orders o
inner join Order_Detail_A a on o.OrderID = a.OrderID and o.OrderDetails_A_ID is not null
union all
select o.OrderID, b.Qty_B as Qty
from Orders o
inner join Order_Detail_B b on o.OrderID = b.OrderID and o.OrderDetails_A_ID is null

答案 2 :(得分:2)

select
  o.OrderDate,
  o.OrderedByID,
  case when o.OrderDetails_A_ID is null then b.ItemDesc_B else a.ItemDesc_A end as ItemDesc,
  case when o.OrderDetails_A_ID is null then b.Qty_B else a.Qty_A end as Qty
FROM
  Orders as O 
  left join OrderDetails_A a on a.OrderID = o.OrderID and o.OrderDetails_A_ID is not null
  left join OrderDetails_B b on b.OrderID = o.OrderID and o.OrderDetails_A_ID is null