SQL Server 中 with tmp 臨時表的用法
----------with臨時表用法,有時候采用臨時表比采用in的效率更高,避免了全表掃描。
實例中實現了查詢普通題、大題、子題目的sql
-----------(對於大題套小題,采用先查小題信息再反查大題相關信息的方式)
一、簡答
1. 會計師的定義?
a。AAAA
b。BBBB
c。CCCC
d。DDDD
二、判斷
2.下面那個是對的?
a。對
b。錯
三、簡答題
3. 看一段文字描述,回答每個小題目:
<1>、第一個小題目
a。AAAA
b。BBBB
c。CCCC
d。DDDD
<2>、第二個小題目
a。AAAA
b。BBBB
c。CCCC
d。DDDD
------------
with tmp as (
select distinct parentID
from QZ_SIM_PAPER_QUESTION
WHERE simPaperID = 205
and isDel <> 1
and ansResult = -1
and queType <> 4
and parentID <> 0
)
select * from
(SELECT t.*
FROM QZ_SIM_PAPER_QUESTION t,tmp
WHERE (t.questionID = tmp.parentID or t.parentID = tmp.parentID) and t.simPaperID = 205) tmp2
union all (SELECT *
FROM QZ_SIM_PAPER_QUESTION
WHERE isDel <> 1 and queType <> 4 and parentID = 0 and simPaperID = 205 and
ansResult = -1) order by parentID,queType
在使用CTE時應注意如下幾點:
1. CTE后面必須直接跟使用CTE的SQL語句(如select、insert、update等),否則,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)
2. CTE后面也可以跟其他的CTE,但只能使用一個with,多個CTE中間用逗號(,)分隔;
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
3. 如果CTE的表達式名稱與某個數據表或視圖重名,則緊跟在該CTE后面的SQL語句使用的仍然是CTE,當然,后面的SQL語句
使用的就是數據表或視圖了;
-- table1是一個實際存在的表
with
table1 as
(
select * from persons where age < 30
)
select * from table1 -- 使用了名為table1的公共表表達式
select * from table1 -- 使用了名為table1的數據表
4. CTE 可以引用自身,也可以引用在同一WITH 子句中預先定義的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 用在屬於批處理的一部分的語句中,那么在它之前的語句必須以分號結尾。
declare @s nvarchar(3)
set @s = 'C%'
; -- 必須加分號
with
t_tree as
(
select CountryRegionCode from person.CountryRegion where Name like @s
)
select * from person.StateProvince where CountryRegionCode in (select * from t_tree)