Use of With Clause in SQL Server

匆匆过客 提交于 2019-12-18 09:08:24

问题


How does with clause work in SQL Server? Does it really give me some performance boost or does it just help to make more readable scripts?

When it is right to use it? What should you know about with clause before you start to use it?

Here's an example of what I'm talking about:

http://www.dotnetspider.com/resources/33984-Use-With-Clause-Sql-Server.aspx


回答1:


Unless you use recursive abilities, a CTE is not better performance-wise than a simple inline view.

It just saves you some typing.

The optimizer is free to decide whether to reevaluate it or not, when it's being reused, and it most cases it decides to reevaluate:

WITH    q (uuid) AS
        (
        SELECT  NEWID()
        )
SELECT  *
FROM    q
UNION ALL
SELECT  *
FROM    q

will return you two different NEWIDs.

Note that other engines may behave differently.

PostgreSQL, unlike SQL Server, materializes the CTEs.

Oracle supports a special hint, /*+ MATERIALIZE */, that tells the optimizer whether it should materialize the CTE or not.




回答2:


I'm not entirely sure about performance advantages, but I think it can definitely help in the case where using a subquery results in the subquery being performed multiple times.

Apart from that it can definitely make code more readable, and can also be used in the case where multiple subqueries would be a cut and paste of the same code in different places.

What should you know before you use it? A big downside is that when you have a CTE in a view, you cannot create a clustered index on that view. This can be a big pain because SQL Server does not have materialised views, and has certainly bitten me before.




回答3:


with is a keyword in SQL which just stores the temporary result in a temporary table. Example:

with a(--here a is the temporary table)
(id)(--id acts as colomn for table a )
 as(select colomn_name from table_name )

select * from a


来源:https://stackoverflow.com/questions/2855940/use-of-with-clause-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!