Use of With Clause in SQL Server

前端 未结 3 1055
北恋
北恋 2020-12-21 11:17

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 ri

3条回答
  •  死守一世寂寞
    2020-12-21 12:06

    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.

提交回复
热议问题