sql-server – 假如在CTE中?
|
我想基于一个编码在CTE中执行select语句.相同下面的对象 ;with CTE_AorB
(
if(condition)
select * from table_A
else
select * from table_B
),CTE_C as
(
select * from CTE_AorB // processing is removed
)
可是我获得了错误.假如在CTE中有其他也许吗?假如没有,是否有办理方案或更好的要领. 感谢. 办理要领实行:;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
)
具有动态搜刮前提的键是确保行使索引,这是一篇关于如那里理赏罚此主题的很是全面的文章: Dynamic Search Conditions in T-SQL by Erland Sommarskog 它涵盖了实行行使多个可选搜刮前提编写查询的全部题目和要领.您必要存眷的首要题目不是代码的一再,而是索引的行使.假如您的查询无法行使索引,它将执行不良.可以行使几种技能,这些技能也许应承也也许不应承行使索引. 这是目次:
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
假如您行使的是恰当版本的SQL Server 2008,则可以行使其他技能,请参阅:Dynamic Search Conditions in T-SQL Version for SQL 2008 (SP1 CU5 and later) 假如您行使的是SQL Server 2008的正确版本,则只需向查询添加OPTION(RECOMPILE),并在运行时将局部变量的值用于优化. 思量到这一点,OPTION(RECOMPILE)将回收此代码(个中没有索引可用于此紊乱的OR): WHERE
(@search1 IS NULL or Column1=@Search1)
AND (@search2 IS NULL or Column2=@Search2)
AND (@search3 IS NULL or Column3=@Search3)
并在运行时优化它(假设只有@ Search2传入一个值): WHERE
Column2=@Search2
而且可以行使索引(假如在Column2上界说了一个索引) (编辑:湖南网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |


