开发者

Use of With Clause in SQL Server

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 开发者_JS百科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


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.


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜