1. 程式人生 > >MSSQL 臨時表和公用表使用案例

MSSQL 臨時表和公用表使用案例

pan -s span cnblogs div count state insert pda

1、臨時表:

1.1)實例1

if(OBJECT_ID(tempdb..#a) IS NOT NULL) drop table #a;
if(OBJECT_ID(tempdb..#b) IS NOT NULL) drop table #b;
SELECT name into #a from syscolumns a with(nolock) where id=OBJECT_ID(NewsLetterSystem_Subscriber);
SELECT name into #b from syscolumns b  where id=OBJECT_ID(tmpContact_130828005535769_5243_f0b7
); select * from #a,#b where #a.name=#b.name;

1.2) 實例2

if(OBJECT_ID(tempdb..#a) IS NOT NULL) drop table #a;
select * into #a from Categories;
select * from #a;

2、公用表:

2.1)實例1

with
cr as
(
   select CountryRegionCode from person.CountryRegion where Name like C%
)

select
* from person.StateProvince where CountryRegionCode in (select * from cr) --其中cr是一個公用表表達式,該表達式在使用上與表變量類似

2.2) 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)

2.3)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

2.4)實例4

with ta as (
 SELECT name  from syscolumns a with(nolock) where id=OBJECT_ID(NewsLetterSystem_Subscriber)
),
tb as
(
SELECT name from syscolumns b  where id=OBJECT_ID(tmpContact_130828005535769_5243_f0b7)
)
select * from ta,tb where ta.name=tb.name

MSSQL 臨時表和公用表使用案例