Thursday, May 23, 2013

Common Table Expressions

A common table expression (CTE) can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query. Unlike a derived table, a CTE can be self-referencing and can be referenced multiple times in the same query.
A CTE can be used to:
  • Create a recursive query.
  • Substitute for a view when the general use of a view is not required; that is, you do not have to store the definition in metadata.
  • Enable grouping by a column that is derived from a scalar subselect, or a function that is either not deterministic or has external access.
  • Reference the resulting table multiple times in the same statement.

    The basic syntax structure for a CTE is:

    WITH expression_name [ ( column_name [,...n] ) ]
    AS
    ( CTE_query_definition )

    The list of column names is optional only if distinct names for all resulting columns are supplied in the query definition.
    The statement to run the CTE is:
    SELECT <column_list>
    FROM expression_name;

    Example:------

    WITH cte_data(country,sal)
    AS
    (
    SELECT country,SUM(sal)
    FROM tbl_groupingSet
    GROUP BY country
    )

    SELECT * FROM cte_data

    CTE with multiple references

    ;WITH cte_data_1(country,sal)
    AS
    (
    SELECT country,SUM(sal)
    FROM tbl_groupingSet
    GROUP BY country
    ),
    cte_data_2(country,sal)
    AS
    (
    SELECT country,SUM(sal)
    FROM tbl_groupingSet
    GROUP BY country
    )
    SELECT * FROM cte_data_1 CROSS JOIN cte_data_2

    Bydefault Recursion level is 100

    CTEs recursion level crosses the limit then following error is thrown by SQL Server engine:
    Msg 530, Level 16, State 1, Line 11
    The statement terminated. The maximum recursion 100 has been exhausted before statement completion.

    you can change the level by using the MAXRECURSION option/hint. The recursion level ranges from 0 and 32,767 

    DECLARE
        @startDate DATETIME,
        @endDate DATETIME

    SET @startDate = '11/10/1985'
    SET @endDate = '03/25/2012'

    ; WITH CTE AS (
        SELECT
            YEAR(@startDate) AS 'yr',
            MONTH(@startDate) AS 'mm',
            DATENAME(mm, @startDate) AS 'mon',
            DATEPART(d,@startDate) AS 'dd',
            @startDate 'new_date'
        UNION ALL
        SELECT
            YEAR(new_date) AS 'yr',
            MONTH(new_date) AS 'mm',
            DATENAME(mm, new_date) AS 'mon',
            DATEPART(d,@startDate) AS 'dd',
            DATEADD(d,1,new_date) 'new_date'
        FROM CTE
        WHERE new_date < @endDate
        )
    SELECT yr AS 'Year', mon AS 'Month', count(dd) AS 'Days'
    FROM CTE
    GROUP BY mon, yr, mm
    ORDER BY yr, mm
    OPTION (MAXRECURSION 32767) 
    Reverse a string without using TSQL’s REVERSE() function
    DECLARE @StringToReverse VARCHAR(55)
    SET @StringToReverse = 'Sandeep'
     
    ;WITH cte AS (
          SELECT @StringToReverse AS string, CAST('' AS VARCHAR(55)) AS revStr, LEN(@StringToReverse) AS ln
          UNION ALL
          SELECT SUBSTRING(string,0,ln) AS string, CAST(revStr + SUBSTRING(string,ln,1) AS VARCHAR(55)) AS revStr, ln-1 AS ln
          FROM cte
          WHERE ln >= 1)
    SELECT @StringToReverse AS String, revStr,ln
    FROM cte
    WHERE ln = 0
  •  
CTE /Temp Table/Table variable


 
CTE:(Common Table Expression)
A common table expression (CTE) can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query. Unlike a derived table, a CTE can be self-referencing and can be referenced multiple times in the same query.


Temp tables 
1. The table "exists" - that is, it's materialized as a table, at least in memory, which contains the result set and can be reused.
2. In some cases, performance can be improved or blocking reduced when you have to perform some elaborate transformation on the data - for example, if you want to fetch a 'snapshot' set of rows out of a base table that is busy, and then do some complicated calculation on that set, there can be less contention if you get the rows out of the base table and unlock it as quickly as possible, then do the work independently. In some cases the overhead of a real temp table is small relative to the advantage in concurrency.
Table Variables
 A table variable goes out of scope immediate after the batch ends -- just like regular variables. This means you don't have to explicitly drop them at the end of scripts.
Table variable and Temp table both resides in TempDB.
It is not required to drop Table variable after the usage.
  • Table variables can not have Non-Clustered Indexes
  • You can not create constraints in table variables
  • You can not create default values on table variable columns
  • Statistics can not be created against table variables

Advantages of derived tables: 
1. A derived table is part of a larger, single query, and will be optimized in the context of the rest of the query. This can be an advantage, if the query optimization helps performance (it usually does, with some exceptions). Example: if you populate a temp table, then consume the results in a second query, you are in effect tying the database engine to one execution method (run the first query in its entirety, save the whole result, run the second query) where with a derived table the optimizer might be able to find a faster execution method or access path.
2. A derived table only "exists" in terms of the query execution plan - it's purely a logical construct. There really is no table.
     

No comments:

Post a Comment