美文网首页
sql with as的用法

sql with as的用法

作者: 是归人不是过客 | 来源:发表于2018-11-19 16:39 被阅读85次

    一、WITH AS 的含义
    WITH AS 短语, 也叫做子查询部分(subqery factoring),可以定义一个SQL片段,改片段回被整个SQL语句用到。可以使SQL语句的可读性更高,也可以再UNION ALL的不同部分,作为提供数据部分。
    二.使用方法
    先看下面一个嵌套的查询语句:
    select * from person.StateProvince where CountryRegionCode in
    (select CountryRegionCode from person.CountryRegion where Name like 'C%')
    上面的查询语句使用了一个子查询。虽然这条SQL语句并不复杂,但如果嵌套的层次过多,会使SQL语句非常难以阅读和维护。因此,也可以使用表变量的方式来解决这个问题,SQL语句如下:
    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)
    虽然上面的SQL语句要比第一种方式更复杂,但却将子查询放在了表变量@t中,这样做将使SQL语句更容易维护,但又会带来另一个问题,就是性能的损失。由于表变量实际上使用了临时表,从而增加了额外的I/O开销,因此,表变量的方式并不太适合数据量大且频繁查询的情况。为此,在SQL Server 2005中提供了另外一种解决方案,这就是公用表表达式(CTE),使用CTE,可以使SQL语句的可维护性,同时,CTE要比表变量的效率高得多。

    三、下面是CTE的语法:
    [ WITH <common_table_expression> [ ,n ] ]
    <common_table_expression>::=
    expression_name [ ( column_name [ ,n ] ) ]
    AS
    ( CTE_query_definition )
    现在使用CTE来解决上面的问题,SQL语句如下: *************重点
    with
    cr as
    (
    select CountryRegionCode from person.CountryRegion where Name like 'C%'
    )

    select * from person.StateProvince where CountryRegionCode in (select * from cr)
    其中cr是一个公用表表达式,该表达式在使用上与表变量类似,只是SQL Server 2005在处理公用表表达式的方式上有所不同。

    在使用CTE时应注意如下几点:

    1. CTE后面必须直接跟使用CTE的SQL语句(如select、insert、update等),否则,CTE将失效。如下面的SQL语句将无法正常使用CTE:

    with
    cr as
    (
    select CountryRegionCode from person.CountryRegion where Name like 'C%'
    )
    select * from person.CountryRegion -- 应将这条SQL语句去掉

    -- 使用CTE的SQL语句应紧跟在相关的CTE后面 --
    select * from person.StateProvince where CountryRegionCode in (select * from cr)

    1. CTE后面也可以跟其他的CTE,但只能使用一个with,多个CTE中间用逗号(,)分隔,如下面的SQL语句所示:

    with
    cte1 as
    (
    select * from table1 where name like 'abc%'
    ),
    cte2 as
    (
    select * from table2 where id > 20
    ),
    cte3 as
    (
    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

    1. 如果CTE的表达式名称与某个数据表或视图重名,则紧跟在该CTE后面的SQL语句使用的仍然是CTE,当然,后面的SQL语句使用的就是数据表或视图了,如下面的SQL语句所示:
      -- table1是一个实际存在的表

    with
    table1 as
    (
    select * from persons where age < 30
    )
    select * from table1 -- 使用了名为table1的公共表表达式
    select * from table1 -- 使用了名为table1的数据表

    相关文章

      网友评论

          本文标题:sql with as的用法

          本文链接:https://www.haomeiwen.com/subject/dulafqtx.html