SQL Server - 重用以前的查询 - 与Linq类似的逻辑

时间:2016-12-06 11:22:28

标签: c# sql-server linq

我正在尝试编写以实现以下查询的逻辑:

select ......
from (select ..... from ... complex and long query #1) R1
     (select ..... from ... complex and long query #2) R2
Where
  NOT ( @DateStart > R2.IstEnde OR @DateEnd <= R2.IstStart)
OR 
(
    (select count(*) 
     from R2  // <---- BUG IS HERE
     Where R2.IsOutsideTaskTimeFrame = 1 AND R2.IsManuallyFixed = 1
    ) > 0
)
order BY R2.PersonName, R1.YearOfWeek, R1.Week 

哪个显然不起作用,因为我正在尝试&#34;重复使用&#34; &#34; count()&#34;中的R2条件。

我写的是基于&#34; .NET Linq&#34;逻辑,我们可以&#34;重用&#34;上一个查询。

我是否可以写出这个&#34;重用&#34;的逻辑上一个查询而不是再重复一次?

2 个答案:

答案 0 :(得分:7)

也许您正在寻找CTE - Common Table Expression

;WITH R1 AS
(SELECT ...)
,R2 AS
(SELECT ...)
SELECT * FROM R1
... use R1 and R2 like any other table here (it's called "derived table")

如果在独立查询中需要结果,则可以填充声明的表变量或临时表。

答案 1 :(得分:0)

您可以使用CTE定义可在代码范围内多次使用的基本查询:

WITH Sales_CTE (returnParam1, returnParam2, ...)
AS
-- Define the CTE query.
(
    select ..... from ... complex and long query #2 
)     

或者你可以创建一个用户定义的函数,它获取params并返回结果,然后多次调用它:

CREATE FUNCTION dbo.ufnGetInventoryStock(param1 int, ...)  
RETURNS int   
AS    
RETURN ( 
    select ..... from ... complex and long query #2  
  )