临时表使用方法

 

SQL SERVER2000中,建立临时表方式有3种:

1create table #table_name(field1 type,field2 type,..........)

     insert into #table_name values(..............)

     select * from #table_name

2create table tempdb.table_name(field1 type,field2 type,..........)

     insert into #table_name values(..............)

     select * from #table_name

3)select * into #temp from (select * from Func) A

   select * from #temp

   drop table #temp

注:

(1)临时表的特点为建立的临时表由创建者使用,多个人可以同时运行该条语句,而不必担心表名重复。当退出数据库或事务被提交时,表自动删除。建立的表需要手工删除,和普通的表的区别是:把表放在了数据库的一个临时空间里,如果不手工删除,当数据库重起时,数据库管理系统会自动将其删除。

(2)临时表有两种类型:本地和全局。它们在名称、可见性以及可用性上有区别。本地临时表的名称以单个数字符号 (#) 打头;它们仅对当前的用户连接是可见的;当用户从 SQL Server 实例断开连接时被删除。全局临时表的名称以两个数字符号 (##) 打头,创建后对任何用户都是可见的,当所有引用该表的用户从 SQL Server 断开连接时被删除。

(3)有另外一种临时表,创建方式:

declare @table_name table (field1 type,field2 type,.......... )  

这种临时表当语句结束时释放临时表一个会话可同时创建几个相同名字的表,但不能在同一条语句中声明几个同名的临时表。用法如下:

SET   QUOTED_IDENTIFIER   ON    
  GO  
  SET   ANSI_NULLS   ON    
  GO  
  create   proc   spGetTreeVar   (@ParentID   int   )  
  as  
  begin  
  set   nocount   on  
      /*
如果不是SQLSERVER2000可以用临时表*/  
  declare   @tmp1     table   (   ParentID   int   ,   ID   int   ,   isclass   int   )  
  declare   @tmp2     table   (   ParentID   int   ,   ID   int   ,   isclass   int   )  
  declare   @tmp3     table   (   ParentID   int   ,   ID   int   ,   isclass   int   )  
       
  insert   @tmp1   select   ParentID,ID   ,IsCls     from   Variables   where       ParentID   =   @ParentID   and   IsDelete   =   0  
  insert   @tmp3   select   ParentID,ID   ,IsCls     from   Variables   where       ParentID   =   @ParentID   and   IsDelete   =   0  
   
      /*
循环的次数等于树的深度*/  
  while   exists(select   *   from   @tmp1   where   isclass   =   1   )  
  begin  
  insert   @tmp2   select   a.ParentID,a.ID,a.IsCls     from   Variables   a,@tmp1   b   where       a.ParentID   =   b.ID   and   IsDelete   =   0  
          /*@tmp2
表中存本次查询的层次的所有结点*/  
  delete   from   @tmp1   where   IsClass   =   1    
          /*@tmp1
表中最终存的是叶子结点*/  
  insert   @tmp1   select   *   from   @tmp2  
          /*@tmp3
表中最保存每次查到的子孙*/  
  insert   @tmp3   select   *   from   @tmp2  
          delete   from   @tmp2  
  end      
  select   Distinct   Variables.*   from   Variables   inner   join   @tmp1   b   on   Variables.ID   =   b.ID    
  set   nocount   off  
  end  
   
  GO  
  SET   QUOTED_IDENTIFIER   OFF    
  GO  
  SET   ANSI_NULLS   ON    
  GO  

判断表明是否已存

判断普通表:

if exists(select * from dbo.sysobjects where id = object_id(N'表名') and OBJECTPROPERTY(id,N'IsUserTable')=1)

print 'exists'

IF (OBJECT_ID('表名') IS not NULL)

print 'exists'

 

判断临时表:

if object_id('tempdb..表名') is not null

print 'exists'

或者:if object_id('表名') is not null

print 'exists'

posted on 2008-08-09 09:24  张皓  阅读(598)  评论(0编辑  收藏  举报

导航