我需要使用相同的派生表运行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个表的数据集。
由于
答案 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
...