MSSQL 临时表和公用表使用案例
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
ps:将一个库中数据插到另一个库中:
语句:
insert into b.dbo.b
select * from a.dbo.a
实例1:
insert into dbname1.dbo.tabname1 select * from dbname2.dbo.tabname2
判断临时表是否存在sql:
if(OBJECT_ID('tempdb..#c') is not null) drop table #c
if(OBJECT_ID('tempdb..#e') is not null) drop table #e if(OBJECT_ID('tempdb..#newc') is not null) drop table #newc
分类:
SQL Server技术
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
2015-05-19 android 不同Activity之间数据传递