if else within CTE?

前端 未结 4 2134
孤独总比滥情好
孤独总比滥情好 2021-01-02 07:51

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
           


        
4条回答
  •  既然无缘
    2021-01-02 08:15

    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
    

提交回复
热议问题