在不同的查询中重用查询结果

时间:2015-04-19 11:30:30

标签: sql sql-server-2008-r2

我有2个查询需要一个接一个地运行。第一个返回work order的单个值,下一个返回所有相关的序列号:

--Get the work order
SELECT * FROM WorkOrder w WHERE w.WorkOrderName = 'test wo';
--Get related serial numbers
SELECT * FROM SerialNumber WHERE SerialNumber.WorkOrderId = w.Id;

是否可以在同一个上下文中运行两个查询,以便我可以在第二个查询中使用w变量并获得2个结果集:
enter image description here

4 个答案:

答案 0 :(得分:1)

使用IN(或EXISTSJOIN):

SELECT sn.*
FROM SerialNumber sn
WHERE sn.WorkOrderId IN (SELECT w.WorkOrderId
                         FROM WorkOrder w JOIN
                              Product p
                              ON p.Id = w.ProductId
                         WHERE w.WorkOrderName = 'test wo'
                        );

如果您希望第一个表中的所有列加上序列号,请使用join

SELECT w.WorkOrderId
FROM WorkOrder w JOIN
     Product p
     ON p.Id = w.ProductId JOIN
     SerialNumber sn
     ON sn.WorkOrderId = w.WorkOrderId
WHERE w.WorkOrderName = 'test wo';

注意:我猜测WorkOrder中的id列是什么。此外,您应列出所需的列,而不是使用SELECT *

答案 1 :(得分:0)

您可以使用变量

declare @WorkOrderId int -- Or what ever type it is

--Get the work order
SELECT @WorkOrderId = w.Id FROM WorkOrder w WHERE w.WorkOrderName = 'test wo';

--Get related serial numbers
SELECT * FROM SerialNumber WHERE SerialNumber.WorkOrderId = @WorkOrderId;

答案 2 :(得分:0)

SELECT * FROM WorkOrder w 
WHERE w.WorkOrderName = 'test wo';

SELECT sn.* FROM SerialNumber sn
 JOIN WorkOrder wo
  ON sn.WorkOrderId = wo.Id
 WHERE wo.WorkOrderName = 'test wo';

或者你可以使用临时表......

IF OBJECT_ID('tempdb..#wo') IS NOT NULL DROP TABLE #wo

SELECT * INTO #wo FROM WorkOrder w 
WHERE w.WorkOrderName = 'test wo';

SELECT sn.* FROM SerialNumber sn
 JOIN #wo wo
  ON sn.WorkOrderId = wo.Id

答案 3 :(得分:0)

如果你想要两个结果并在第二个查询中使用w.Id,你需要在最终结果中有一个字段来识别结果集,如下所示:

SELECT 'Results 1' As resultSet, Id As Col1, WorkOrderName As Col2, Created As Col3
FROM WorkOrder w
WHERE w.WorkOrderName = 'test wo'
UNION ALL
SELECT 'Results 2' As resultSet, Id As Col1, WorkOrderId As Col2, SerialValue As Col3
FROM SerialNumber 
WHERE SerialNumber.WorkOrderId IN (SELECT w.Id
                FROM WorkOrder w 
                WHERE w.WorkOrderName = 'test wo')