SqlServer和MySQL临时表创建与临时表变量使用

sqlserver临时表与永久表类似,但不再使用时会自动删除。

sqlserver临时表特点如下:

创建表时在表名前加"前缀"符号。

临时表利用虚拟内存,减少硬盘I/O次数,提高系统效率。

sqlserver临时表有两种类型:

1、本地临时表

创建临时表时表名称以(#)打头,仅对当前用户连接可见,断开连接时自动删除。

在一次连接中多次创建会报错,断开连接即删除。

例如下:

create table #temp
(
    id int,
    name nvarchar(200)
)

insert into #temp(id,name) values
(1,'one')

select * from #temp

2、全局临时表

创建临时表时表名称以(##)开头,创建后对任何数据库连接都是可见的,当对该表的所有引用都断开时自动删除。

在多个连接中多次创建报错,除非已删除。

例如下:

create table ##tempone
(
id int,
name nvarchar(100)
)

insert into ##tempone(id,name) values(1,'one');
select * from ##tempone;

Sqlserver临时表变量的使用:

类似于临时表,比临时表更临时。

declare @temptb table(
id int,
name nvarchar(100)
)

insert into @temptb(id,name) values
(1,'one');
select * from @temptb;

MySql临时表创建使用:

理论上mysql临时表在一次SQL执行后会被自动回收,但是可以用drop保证其被确实执行;

mysql临时表类似于sqlserver的本地临时表。

create TEMPORARY table temptbone
(
id int,
name varchar(200)
);

insert into temptbone(id,name) values(1,'one');

select * from temptbone;

回收

DROP TABLE IF EXISTS temptbone;

猜你喜欢

转载自blog.csdn.net/qq_38261174/article/details/100930674