views:

206

answers:

3

I want to execute select statement within CTE based on a codition. something like below

;with CTE_AorB
(
  if(condition)
    select * from table_A
   else
    select * from table_B
),
CTE_C as
(
   select * from CTE_AorB // processing is removed
)

But i get error on this. Is it possible to have if else within CTEs? If not is there a work around Or a better approach.

Thanks.

+2  A: 

try:

;with CTE_AorB
(
    select * from table_A WHERE (condition true)
    union all
    select * from table_B WHERE NOT (condition true)
),
CTE_C as
(
   select * from CTE_AorB // processing is removed
)

the key with a dynamic search condition is to make sure an index is used, Here is a very comprehensive article on how to handle this topic:

Dynamic Search Conditions in T-SQL by Erland Sommarskog

it covers all the issues and methods of trying to write queries with multiple optional search conditions. This main thing you need to be concerned with is not the duplication of code, but the use of an index. If your query fails to use an index, it will preform poorly. There are several techniques that can be used, which may or may not allow an index to be used.

here is the table of contents:

  Introduction
      The Case Study: Searching Orders
      The Northgale Database
   Dynamic SQL
      Introduction
      Using sp_executesql
      Using the CLR
      Using EXEC()
      When Caching Is Not Really What You Want
   Static SQL
      Introduction
      x = @x OR @x IS NULL
      Using IF statements
      Umachandar's Bag of Tricks
      Using Temp Tables
      x = @x AND @x IS NOT NULL
      Handling Complex Conditions
   Hybrid Solutions – Using both Static and Dynamic SQL
      Using Views
      Using Inline Table Functions
   Conclusion
   Feedback and Acknowledgements
   Revision History

if you are on the proper version of SQL Server 2008, there is an additional technique that can be used, see: Dynamic Search Conditions in T-SQL Version for SQL 2008 (SP1 CU5 and later)

If you are on that proper release of SQL Server 2008, you can just add OPTION (RECOMPILE) to the query and the local variable's value at run time is used for the optimizations.

Consider this, OPTION (RECOMPILE) will take this code (where no index can be used with this mess of ORs):

WHERE
    (@search1 IS NULL or Column1=@Search1)
    AND (@search2 IS NULL or Column2=@Search2)
    AND (@search3 IS NULL or Column3=@Search3)

and optimize it at run time to be (provided that only @Search2 was passed in with a value):

WHERE
    Column2=@Search2

and an index can be used (if you have one defined on Column2)

KM
You mean UNION ALL?
gbn
@gbn, duh, yea fixed that!
KM
me again. OPTION (RECOMPILE) is in SQL 2000+... OPTIMISE FOR UNKNOWN is new in SQL Server 2008 which allows plan caching that RECOMPILE doesn't
gbn
OPTION (RECOMPILE) isn't new, but the fact that it will consider the actual runtime values of local variables is new starting in SQL 2008 (SP1 CU5 and later)
KM
+3  A: 

Never ever try to put conditions like IF inside a single query statements. Even if you do manage to pull it off, this is the one sure-shot way to kill performance. Remember, a single statement means a single plan, and the plan will have to be generated in a way to satisfy both cases, when condition is true and when condition is false, at once. This usually result in the worse possible plan, since the 'condition' usually creates mutually exclusive access path for the plan and the union of the two results in always end-to-end table scan.

Your best approach, for this and many many other reasons, is to pull the IF outside of the statement:

if(condition true)
    select * from table_A
else
    select * from table_B
Remus Rusanu
[the limitation of the `IF-ELSE` pattern](http://www.sommarskog.se/dyn-search-2005.html#IF) is handling every possible combination, but if this is just the two cases then this might be the way to go.
KM
i am kind of a beginner in t-sql. all my t-sql knowledge has come by asking questions on stackoverflow. Thanks for the suggestion about performance. Will dig further into this. For now an up vote from me.
stackoverflowuser
+1  A: 

I think the IF ELSE stuff might have poor caching if your branch condition flips. Maybe someone more knowledgeable can comment.

Another way would be to UNION ALL with the WHERE clauses as suggested by others. The UNION ALL would replace the IF ELSE

uosɐſ
[some issues related to caching using the `IF-ELSE` pattern are covered in here](http://www.sommarskog.se/dyn-search-2005.html#IF)
KM