临时表:临时表是一种简单的临时存在数据库系统中的表格,当数据库的链接或退出登录时,会被自动删除。

Transact_SQL在TempDB中创建临时表,这个数据库是在你安装SQL-SERVER时创建的,创建临时表可以使用两种语法格式。

SYNTAX:

SYNTAX1:

create table #table_name(fild1 datatype,
                            .
                            .
                            .
                        fieldn datatype)

--表名开头的#标志是 SQL 用以标识临时表的标志
--临时表只有创建者可以使用,可以多个用户同时创建相同的临时表,多个用户可同时运行下列代码:
create table #albums(
artist char((30),
album_name char(50),
media_type int)
go

--每一个用户都可以放心地插入、更新、删除表中的数据而不必担心其它的用户使该表中的数据失效。
--删除临时表
drop table #albums
go

--如果用户退出SQL-SERVER,临时表也会被退出

SYNTAX:

SYNTAX2:

create table tempdb..table_name(fild1 datatype,
                                    .
                                fieldn datatype)
--当用户退出 SQL 或切断联接时该表不会被自动地删除。

这两种格式的临时表的确是货真价实的临时的表。

--MUSIC数据库中创建以下三个表:ARTISTS 、 MEDIA、RECORDINGS
create table ARTISTS (
name char(30),
homebase char(40),
style char(20),
artist_id int)
go

create table MEDIA (
media_type int,
description char(30),
price float)
go

create table RECORDINGS (
artist_id int,
media_type int,
title char(50),
year int)
go

--在tempDB数据库中创建一个临时表,向表中插入虚拟法人数据后,退出登录,然后重新登录SQL SERVER。
create table #albums (
artist char(30),
album_name char(50),
media_type int)
go

insert #albums values ("The Replacements", "Pleased To Meet Me", 1)
go

Exit

select * from #albums
go

--当前数据库中不存在该表

--使用语法2创建表
create table tempdb..albums (
artist char(30),
album_name char(50),
media_type int)
go

insert #albums values ("The Replacements", "Pleased To Meet Me", 1)
go

--在退出登录并重新登录进入以后,切换到你在CREATE TABLE TEMPDB..ALBUMS()命令中指明的数据库
select * from #albums
go

--可以得到结果

        临时表的最为通常的用途:用于暂时存贮从查询中返回的数据,这些数据可以在其它的查询中使用。

例如:选出了所有的居住在 Nashville 的艺术家的记录信息

create table #temp_info(
name char(30),
homebase char(40),
style char(20),
artist_id int)

insert #temp_info
select * from ARTISTS where homebase="Nashville"

select RECORDINGS.* from RECORDINGS, ARTISTS
where RECORDINGS.artist_id = #temp_info.artist_id

go

--另一种写法
select ARTISTS.* from ARTISTS, RECORDINGS where ARTISTS.homebase = "Nashville"
go

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐