开发者

Derived table used several times

开发者 https://www.devze.com 2023-04-13 09:59 出处:网络
I need to run 3 consecutive queries using the same derived table... I\'m using MS SQL Server 2008 Select a,b,c from categories inner join (select x,y,z from derivedTable where…) …

I need to run 3 consecutive queries using the same derived table... I'm using 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…) …开发者_开发技巧

Is there a way to run the 3 sql queries at the same time in a way the derived table

(select x,y,z from derivedTable where ...) 

is executed only once?

I’m using .net so... I’m wondering if I could return the 3 tables and load a dataset with the 3 tables.

Thanks


You could use WITH:

Note: As pointed by @Martin WITH is evaluated several times so the correct solution is the temporary table.

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
 ...

or a temporary table:

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
 ...
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号