码迷,mamicode.com
首页 > 数据库 > 详细

sql Server中临时表与数据表的区别

时间:2017-07-17 14:33:51      阅读:319      评论:0      收藏:0      [点我收藏+]

标签:删除   dhx   into   wce   vpn   htm   from   jna   mba   

sql server 中临时表与数据表的区别

1、如何判断临时表和数据表已生成

--如何判断临时表是否已创建---
if exists(select * from tempdb..sysobjects where id=object_id(tempdb..#Temp_Student))
    begin
        print 存在临时表;
    end
else
    begin
        print 不存在临时表;
    end
--如何判断数据表是否已创建---
if exists(select * from sys.tables where name=Data_Student)
    begin
        print 存在数据表;
    end
else
    begin
        print 不存在数据表;
    end

其中,临时表创建后默认在tempdb(临时数据库中)的sysobjects中,而数据表创建在当前数据库的sys.tables中

2、如何创建临时表和数据表

  当我们检查到临时表、数据表不存在时,一般进行创建临时表、数据表;存在时,可进行删除或清空数据

--1、如何判断临时表是否已创建---
if exists(select * from tempdb..sysobjects where id=object_id(tempdb..#Temp_Student))
    begin
        --print ‘存在临时表‘;
        --删除临时表(包括表结构)--
        --drop table #Temp_Student        
        --删除临时表(不包括表结构)--
        truncate table #Temp_Student
    end
else
    begin
        --print ‘不存在临时表‘;
        create table #Temp_Student
        (
            Uid int identity(1,1) primary key,
            Age int not null,
            Name varchar(20) not null,
        )
    end
    
--2、如何判断数据表是否已创建---
if exists(select * from sys.tables where name=Data_Student)
    begin
        --print ‘存在数据表‘;
        --删除数据表(包括表结构)--
        --drop table Data_Student        
        --删除数据表(不包括表结构)--
        truncate table Data_Student
    end
else
    begin
        --print ‘不存在数据表‘;
        --不存在时,创建数据表--
        create table Data_Student
        (
            Uid int identity(1,1) primary key,
            Age int not null,
            Name varchar(20) not null,
        )
    end

3、如何添加临时表和数据表的数据

-----3、如何插入数据----
--1)插入数据到临时表---
insert into #Temp_Student(Age,Name) values(21,张三),(22,李四) 
--2)插入数据到数据表---
insert into Data_Student(Age,Name) values(23,王五),(24,赵六)

4、如何查询临时表和数据表数据

-----4、如何查询数据-------    
--1)查询临时表--
select * from #Temp_Student
--2)查询临时表--
select * from Data_Student

5、查询后结果

技术分享

sql Server中临时表与数据表的区别

标签:删除   dhx   into   wce   vpn   htm   from   jna   mba   

原文地址:http://www.cnblogs.com/xielong/p/7194051.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!