当前位置: 代码网 > it编程>数据库>MsSqlserver > SQL创建临时表的两种方法

SQL创建临时表的两种方法

2024年10月17日 MsSqlserver 我要评论
在 sql 中,创建临时表可以有多种方法,取决于你想要实现的功能和数据库的类型。以下是两种常见的方法:1. 使用with子句(常用于 cte,公用表表达式)如果你不需要在多个查询中重复使用临时表,并且

在 sql 中,创建临时表可以有多种方法,取决于你想要实现的功能和数据库的类型。以下是两种常见的方法:

1. 使用 with 子句(常用于 cte,公用表表达式)

如果你不需要在多个查询中重复使用临时表,并且只是想在一个查询中使用中间结果,可以使用 with 子句。这种方法不会真正创建物理临时表,而是生成一个临时的结果集。

with temp as (
    select column1, column2
    from original_table
    where conditions
)
select *
from temp
where other_conditions;

2. 使用 create temporary table

如果你需要创建一个在整个会话中都可以使用的临时表,可以使用 create temporary table 语句。这会创建一个物理上的临时表,存储在会话或连接的内存中,通常在会话结束时自动删除。

create temporary table temp_table as
select column1, column2
from original_table
where conditions;

-- 然后可以在会话中随时使用 temp_table
select *
from temp_table
where other_conditions;

什么时候使用 with 子句 vs. create temporary table

  • with 子句:适用于单个查询中的中间结果集,特别是在你不需要重复使用临时结果集时。通常更简洁,且性能开销较低。
  • create temporary table:适用于你需要在多个查询或整个会话中使用相同的数据集,并且需要持久性超过单个查询的情况。

根据你的需求,选择合适的方法来创建临时表。

查询临时表

select * from #临时表名;
select * from ##临时表名;

删除临时表

drop table #临时表名;
drop table ##临时表名;

使用说明

drop table #tmp   --删除临时表#tmp
create table #tmp --创建临时表#tmp
(
    id   int identity (1,1)     not null, --创建列id,并且每次新增一条记录就会加1
    wokno                varchar(50),   
    primary key (id)      --定义id为临时表#tmp的主键      
);
select * from #tmp    --查询临时表的数据
truncate table #tmp --清空临时表的所有数据和约束

example

if object_id('tempdb..#jimmy') is not null begin
drop table #jimmy;
end
select * 
into #jimmy
from table
where 1=1

到此这篇关于sql创建临时表的两种方法的文章就介绍到这了,更多相关sql创建临时表内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com