如何在CTE中的where子句之前应用条件

时间:2014-04-25 10:37:37

标签: sql sql-server sql-server-2008 tsql

我有一个关于选择查询的问题,我正在使用CTE执行查询,我的查询是如何在Where子句之前在CTE中应用条件,

Temp

    Id | Title
  --------------    
    1  |  ABCD
    2  |  ABCD
    3  |  AB
    4  |  CD
    5  |  DA

Declare @Count int,@search nvarchar(50)

Select @search ='AB'

set @Count =1

WITH TempResult as          
    (              
        Select * from Temp
    )   
SELECT  * from TempResult

现在我希望当Count = 1然后Record会根据@search变量进行搜索,否则不会,Canany一个人帮我这个但是记得我想要CTE中的任何条件语句都没有意味着没有重复CTE

4 个答案:

答案 0 :(得分:2)

看起来像

WITH TempResult as          
    (              
        Select * from Temp WHERE @count <> 1 OR Title = @Search
    )   
SELECT  * from TempResult

答案 1 :(得分:2)

我认为这就是你所追求的目标:

WITH TempResult AS
(
 SELECT * FROM Temp WHERE (@Count<>1 OR Title LIKE '%'+@Search+'%')
)
SELECT * FROM TempResult

<强>解释

当@Count!= 1时,记录将仅使用Title LIKE '%'+@Search+'%' 进行过滤。

更确切地说:

@Count = 1时,它将用于WHERE子句的第二部分。

@Count!= 1时,它不会用于第二部分,因为WHERE子句已经返回true

答案 2 :(得分:2)

尝试:

WITH TempResult as
(
 SELECT * FROM Temp WHERE @Count=1 AND Title LIKE '%'+@Search+'%'
  UNION ALL
 SELECT * FROM Temp WHERE @Count<> 1
)
SELECT * FROM TempResult

答案 3 :(得分:0)

这个怎么样?

WITH TempResult as
(
     SELECT * FROM Temp WHERE (@Count=0) OR (@Count <> 0 AND Title LIKE '%'+@Search+'%')
)
SELECT * FROM TempResult