Use WITHAS in SQL to improve performance-use a common table expression (CTE) to simplify nested SQL statements

Source: Internet
Author: User
1. WITHAS description WITHAS phrase, also known as subqueryfactoring, allows you to do many things and define an SQL segment which will be used by the entire SQL statement. Sometimes, it is to make the SQL statement more readable, or it may be in different parts of UNIONALL, as part of providing data. Special

I. with as, also known AS subquery factoring, allows you to do a lot of things and define an SQL segment, this SQL segment is used by the entire SQL statement. Sometimes, it is to make the SQL statement more readable, or it may be in different parts of UNION ALL, as part of the provided data. Special

1. Meaning of WITH
The with as phrase, also known AS subquery factoring, allows you to do a lot of things and define an SQL segment, which will be used by the entire SQL statement. Sometimes, it is to make the SQL statement more readable, or it may be in different parts of UNION ALL, as part of the provided data.
Especially useful for union all. Because each part of union all may be the same, but if each part is executed once, the cost is too high and the server space is occupied. Therefore, you can use the with as phrase, Hong Kong server, you only need to execute it once. If the table name defined by the with as phrase is called more than twice, the optimizer automatically puts the data obtained by the with as phrase into a TEMP table. If it is called only once, no. The prompt materialize is to forcibly put the data in the with as phrase into a global temporary table. This method improves the speed of many queries.
Ii. Usage
First, let's look at the following nested query statement:

Select * from person. StateProvince where CountryRegionCode in
(Select CountryRegionCode from person. CountryRegion where Name like 'C % ')

The preceding query statement uses a subquery. Although this SQL statement is not complex, if there are too many layers of nesting, it will make the SQL statement very difficult to read and maintain. Therefore, you can use table variables to solve this problem. The SQL statement is as follows:

Declare @ t table (CountryRegionCode nvarchar (3 ))
Insert into @ t (CountryRegionCode) (select CountryRegionCode from person. CountryRegion where Name like 'C % ')

Select * from person. StateProvince where CountryRegionCode
In (select * from @ t)


Although the preceding SQL statement is more complex than the first method, the subquery is placed in the table variable @ t. This will make the SQL statement easier to maintain, however, there will be another problem. The server space is the performance loss. Because the table variables actually use temporary tables, which increases Additional I/O overhead, the table variables are not suitable for large data volumes and frequent queries. Therefore, another solution is provided in SQL Server 2005, which is the common table expression (CTE). Using CTE can make the SQL statement maintainability, CTE is much more efficient than table variables.

The syntax of CTE is as follows:

[ [, N]
: =
Expression_name [(column_name [, n])]
AS
(CTE_query_definition)

Now we use CTE to solve the above problem. The SQL statement is as follows:

With
Cr
(
Select CountryRegionCode from person. CountryRegion where Name like 'C %'
)

Select * from person. StateProvince where CountryRegionCode in (select * from cr)

Cr is a common table expression, which is similar to a table variable in use, but SQL Server 2005 has different processing methods for common table expressions.

Pay attention to the following points when using CTE:
1. The CTE must be followed by the SQL statements that use the CTE (such as select, insert, and update). Otherwise, the CTE will become invalid. The following SQL statement cannot use CTE normally:


With
Cr
(
Select CountryRegionCode from person. CountryRegion where Name like 'C %'
)
Select * from person. CountryRegion -- remove this SQL statement.
-- The SQL statement using CTE should be followed by the relevant CTE --
Select * from person. StateProvince where CountryRegionCode in (select * from cr)


2. The CTE can be followed by other CTE, but only one with can be used. Multiple CTE are separated by commas (,), as shown in the following SQL statement:

With
Cte1
(
Select * from table1 where name like 'abc %'
),
Cte2
(
Select * from table2 where id> 20
),
Cte3
(
Select * from table3 where price <100
)
Select a. * from cte1 a, cte2 B, cte3 c where a. id = B. id and a. id = c. id

3. if the expression name of the CTE is the same as that of a data table or view, the SQL statement followed by the CTE still uses the CTE. Of course, the following SQL statement uses a data table or view, as shown in the following SQL statement:


-- Table1 is an existing table.

With
Table1
(
Select * from persons where age <30
)
Select * from table1 -- a public table expression named table1 is used.
Select * from table1 -- a data table named table1 is used.

4. The CTE can reference itself, or reference the pre-defined CTE in the same WITH clause. Forward references are not allowed.

5. the following clause cannot be used in CTE_query_definition:

(1) COMPUTE or COMPUTE

(2) order by (unless TOP clause is specified)

(3)

(4) OPTION clause with query prompt

(5) FOR XML

(6) FOR BROWSE

6. If you use CTE in a statement that is part of the batch processing, the statement before it must end with a semicolon, as shown in the following SQL:

Declare @ s nvarchar (3)
Set @ s = 'C %'
; -- Add points required
With
T_tree
(
Select CountryRegionCode from person. CountryRegion where Name like @ s
)
Select * from person. StateProvince where CountryRegionCode in (select * from t_tree)

In addition to simplifying nested SQL statements, CTE can also perform recursive calling. This part of content will be introduced in the next article.

Reprinted from:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.