派生表使用了好几次

时间:2011-10-15 11:04:57

标签: sql sql-server sql-server-2008 derived-table

我需要使用相同的派生表运行3个连续查询...我正在使用MS SQL Server 2008

Select a,b,c from categories inner join (select x,y,z from derivedTable where…) …
Select a,b,c from users inner join (select x,y,z from derivedTable where…) …
Select a,b,c from orders inner join (select x,y,z from derivedTable where…) …

有没有办法以派生表

的方式同时运行3个sql查询
(select x,y,z from derivedTable where ...) 

只执行一次?

我正在使用.net所以...我想知道我是否可以返回3个表并加载3个表的数据集。

由于

1 个答案:

答案 0 :(得分:2)

您可以使用WITH

注意:正如@Martin所指出的WITH被评估了几次,所以正确的解决方案就是临时表。

WITH derivedTable (x,y,z)
as
(
    select x,y,z
      from derivedTable
      ...
)
SELECT a, b, c
  FROM users
  join derivedTable on ...
 WHERE ...
union all
SELECT a, b, c
  FROM orders
  join derivedtable on ...
 WHERE ... 
union all
 ...

或临时表:

select x,y,z
  into #derivedTable
  from derivedTable
  ...

SELECT a, b, c
  FROM users
  join #derivedTable on ...
 WHERE ...
union all
SELECT a, b, c
  FROM orders
  join #derivedtable on ...
 WHERE ... 
union all
 ...