经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » MS SQL Server » 查看文章
SQL With As 用法
来源:cnblogs  作者:米卢的教练  时间:2019/10/9 10:51:04  对本文有异议

一.WITH AS的含义

WITH AS短语,也叫做子查询部分(subquery factoring),可以定义一个SQL片断,该SQL片断会被整个SQL语句用到。可以使SQL语句的可读性更高,也可以在UNION ALL的不同部分,作为提供数据的部分。

对于UNION ALL,使用WITH AS定义了一个UNION ALL语句,当该片断被调用2次以上,优化器会自动将该WITH AS短语所获取的数据放入一个Temp表中。而提示meterialize则是强制将WITH AS短语的数据放入一个全局临时表中。很多查询通过该方式都可以提高速度。

二.使用方法 
先看下面一个嵌套的查询语句:

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

上面的查询语句使用了一个子查询。虽然这条SQL语句并不复杂,但如果嵌套的层次过多,会使SQL语句非常难以阅读和维护。因此,也可以使用表变量的方式来解决这个问题,SQL语句如下:

  1. declare @t table(CountryRegionCode nvarchar(3))
  2. insert into @t(CountryRegionCode) (select CountryRegionCode from person.CountryRegion where Name like 'C%')
  3.  
  4. select * from person.StateProvince where CountryRegionCode
  5. in (select * from @t)

虽然上面的SQL语句要比第一种方式更复杂,但却将子查询放在了表变量@t中,这样做将使SQL语句更容易维护,但又会带来另一个问题,就是性能的损失。由于表变量实际上使用了临时表,从而增加了额外的I/O开销,因此,表变量的方式并不太适合数据量大且频繁查询的情况。为此,在SQL Server 2005中提供了另外一种解决方案,这就是公用表表达式(CTE),使用CTE,可以使SQL语句的可维护性,同时,CTE要比表变量的效率高得多。

 

下面是CTE的语法:

  1. [ WITH <common_table_expression> [ ,n ] ]
  2. <common_table_expression>::=
  3. expression_name [ ( column_name [ ,n ] ) ]
  4. AS
  5. ( CTE_query_definition )

现在使用CTE来解决上面的问题,SQL语句如下:

复制代码
  1. with
  2. cr as
  3. (
  4. select CountryRegionCode from person.CountryRegion where Name like 'C%'
  5. )
  6.  
  7. 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:

 
  1. with
  2. cr as
  3. (
  4. select CountryRegionCode from person.CountryRegion where Name like 'C%'
  5. )
  6. select * from person.CountryRegion -- 应将这条SQL语句去掉
  7. -- 使用CTESQL语句应紧跟在相关的CTE后面 --
  8. select * from person.StateProvince where CountryRegionCode in (select * from cr)
 

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

 
  1. with
  2. cte1 as
  3. (
  4. select * from table1 where name like 'abc%'
  5. ),
  6. cte2 as
  7. (
  8. select * from table2 where id > 20
  9. ),
  10. cte3 as
  11. (
  12. select * from table3 where price < 100
  13. )
  14. select a.* from cte1 a, cte2 b, cte3 c where a.id = b.id and a.id = c.id
 

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

 
  1. -- table1是一个实际存在的表
  2.  
  3. with
  4. table1 as
  5. (
  6. select * from persons where age < 30
  7. )
  8. select * from table1 -- 使用了名为table1的公共表表达式
  9. select * from table1 -- 使用了名为table1的数据表
 

4. CTE 可以引用自身,也可以引用在同一 WITH 子句中预先定义的 CTE。不允许前向引用。

 
  1. --使用递归公用表表达式显示递归的多个级别
  2. WITH DirectReports(ManagerID, EmployeeID, EmployeeLevel) AS
  3. (
  4. SELECT ManagerID, EmployeeID, 0 AS EmployeeLevel
  5. FROM HumanResources.Employee
  6. WHERE ManagerID IS NULL
  7. UNION ALL
  8. SELECT e.ManagerID, e.EmployeeID, EmployeeLevel + 1
  9. FROM HumanResources.Employee e
  10. INNER JOIN DirectReports d
  11. ON e.ManagerID = d.EmployeeID
  12. )
  13. SELECT ManagerID, EmployeeID, EmployeeLevel
  14. FROM DirectReports ;
  15.  
  16. --使用递归公用表表达式显示递归的两个级别
  17. WITH DirectReports(ManagerID, EmployeeID, EmployeeLevel) AS
  18. (
  19. SELECT ManagerID, EmployeeID, 0 AS EmployeeLevel
  20. FROM HumanResources.Employee
  21. WHERE ManagerID IS NULL
  22. UNION ALL
  23. SELECT e.ManagerID, e.EmployeeID, EmployeeLevel + 1
  24. FROM HumanResources.Employee e
  25. INNER JOIN DirectReports d
  26. ON e.ManagerID = d.EmployeeID
  27. )
  28. SELECT ManagerID, EmployeeID, EmployeeLevel
  29. FROM DirectReports
  30. WHERE EmployeeLevel <= 2
  31.  
  32. --使用递归公用表表达式显示层次列表
  33. WITH DirectReports(Name, Title, EmployeeID, EmployeeLevel, Sort)
  34. AS (SELECT CONVERT(varchar(255), c.FirstName + ' ' + c.LastName),
  35. e.Title,
  36. e.EmployeeID,
  37. 1,
  38. CONVERT(varchar(255), c.FirstName + ' ' + c.LastName)
  39. FROM HumanResources.Employee AS e
  40. JOIN Person.Contact AS c ON e.ContactID = c.ContactID
  41. WHERE e.ManagerID IS NULL
  42. UNION ALL
  43. SELECT CONVERT(varchar(255), REPLICATE ('| ' , EmployeeLevel) +
  44. c.FirstName + ' ' + c.LastName),
  45. e.Title,
  46. e.EmployeeID,
  47. EmployeeLevel + 1,
  48. CONVERT (varchar(255), RTRIM(Sort) + '| ' + FirstName + ' ' +
  49. LastName)
  50. FROM HumanResources.Employee as e
  51. JOIN Person.Contact AS c ON e.ContactID = c.ContactID
  52. JOIN DirectReports AS d ON e.ManagerID = d.EmployeeID
  53. )
  54. SELECT EmployeeID, Name, Title, EmployeeLevel
  55. FROM DirectReports
  56. ORDER BY Sort
  57.  
  58. --使用 MAXRECURSION 取消一条语句
  59. --可以使用 MAXRECURSION 来防止不合理的递归 CTE 进入无限循环。以下示例特意创建了一个无限循环,然后使用 MAXRECURSION 提示将递归级别限制为两级
  60. WITH cte (EmployeeID, ManagerID, Title) as
  61. (
  62. SELECT EmployeeID, ManagerID, Title
  63. FROM HumanResources.Employee
  64. WHERE ManagerID IS NOT NULL
  65. UNION ALL
  66. SELECT cte.EmployeeID, cte.ManagerID, cte.Title
  67. FROM cte
  68. JOIN HumanResources.Employee AS e
  69. ON cte.ManagerID = e.EmployeeID
  70. )
  71. --Uses MAXRECURSION to limit the recursive levels to 2
  72. SELECT EmployeeID, ManagerID, Title
  73. FROM cte
  74. OPTION (MAXRECURSION 2)
  75. --在更正代码错误之后,就不再需要 MAXRECURSION。以下示例显示了更正后的代码
  76. WITH cte (EmployeeID, ManagerID, Title)
  77. AS
  78. (
  79. SELECT EmployeeID, ManagerID, Title
  80. FROM HumanResources.Employee
  81. WHERE ManagerID IS NOT NULL
  82. UNION ALL
  83. SELECT e.EmployeeID, e.ManagerID, e.Title
  84. FROM HumanResources.Employee AS e
  85. JOIN cte ON e.ManagerID = cte.EmployeeID
  86. )
  87. SELECT EmployeeID, ManagerID, Title
  88. FROM cte
 

 

5. 不能在 CTE_query_definition 中使用以下子句:

  (1)COMPUTE 或 COMPUTE BY

  (2)ORDER BY(除非指定了 TOP 子句)

  (3)INTO

  (4)带有查询提示的 OPTION 子句

  (5)FOR XML

  (6)FOR BROWSE

6. 如果将 CTE 用在属于批处理的一部分的语句中,那么在它之前的语句必须以分号结尾,如下面的SQL所示:

 
  1. declare @s nvarchar(3)
  2. set @s = 'C%'
  3. ; -- 必须加分号
  4. with
  5. t_tree as
  6. (
  7. select CountryRegionCode from person.CountryRegion where Name like @s
  8. )
  9. select * from person.StateProvince where CountryRegionCode in (select * from t_tree)
 
 

来源连接:https://www.cnblogs.com/Niko12230/p/5945133.html

原文链接:http://www.cnblogs.com/crrc/p/11639748.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号