如何判断数据库中是否已经存在某个临时表?

weidegong 2004-04-30 10:10:08
如题
...全文
450 19 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
19 条回复
切换为时间正序
请发表友善的回复…
发表回复
sgwindy 2004-06-15
  • 打赏
  • 举报
回复
经测试,下面一定正确
if exists(select * from tempdb..sysobjects where name='##临时表名称' and xtype='U')
print '存在'
else
print '不存在'
selfrich 2004-05-03
  • 打赏
  • 举报
回复
一、已创建的临时表只存在于tempdb库的用户表中(但不属于tempdb库),而不可能存在于某个其它库的的用户表中; 如为库A创建了一个临时表#m,但在A的表对象中并没有#m,而#m确在tempdb的表对象中(你可以在查询分析器的观察).
二、为任何库创建的临时表,表名均不能重复,因为临时表只存在于tempdb库的用户表中;
三、临时表并不存在父对象,其tempdb..sysobjects.parent_obj=0;
四、还存在临时存储过程等其它对象;所以下列判断方法不完全
IF (OBJECT_ID('TEMPDB..#') IS NOT NULL)
PRINT 'EXISTS'
ELSE
PRINT 'NOT EXISTS'
五、可以用下列方法判断是否存在相应的临时表(#m):

if exists(select 1 from tempdb..sysobjects where name='#m' and xtype='U')
print 'not exists'
else
print 'exists'


kqh0319 2004-05-03
  • 打赏
  • 举报
回复
学习
silversnowjing 2004-05-01
  • 打赏
  • 举报
回复
学习
internetcsdn 2004-05-01
  • 打赏
  • 举报
回复
同意hglhyy(查無此人) ( )
最简单的办法了
vileboy 2004-05-01
  • 打赏
  • 举报
回复
if exists(select 1 from tempdb..sysobjects where left(name,6)='#tbl_t')
print 'not exists'
else
print 'exists'
hglhyy 2004-05-01
  • 打赏
  • 举报
回复
如果知道临时表名,存不存在查询下不就出来了!
weidegong 2004-04-30
  • 打赏
  • 举报
回复
UP一下,确实不能用呀?
lalakid 2004-04-30
  • 打赏
  • 举报
回复
支持ghosthjt(天煞孤星)
测试了,好使
weidegong 2004-04-30
  • 打赏
  • 举报
回复
不行;
if exists (select * from sysobjects where id = object_id(N'[dbo].[#tmp]') and OBJECTPROPERTY(id, N'IsTable') = 1)
print 'yes'
GO
klan 2004-04-30
  • 打赏
  • 举报
回复
if exists (select * from sysobjects where id = object_id(N'[dbo].[你的临时表名]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
print 'yes'
GO
youngby 2004-04-30
  • 打赏
  • 举报
回复
create table #tmp
if @@error<>0 then
print ‘存在’
else begin print ‘不存在’ drop table #tmp end
youngby 2004-04-30
  • 打赏
  • 举报
回复
create table #tmp
if @@error<>0 then
print ‘存在’
else print ‘不存在’
Mybeautiful 2004-04-30
  • 打赏
  • 举报
回复
还有一个方法,
就是 drop table #tem

检查@@ERror_Statue 就知道了
sysmaster 2004-04-30
  • 打赏
  • 举报
回复
#dd 是我用来测试的临时表
sysmaster 2004-04-30
  • 打赏
  • 举报
回复
if object_id('tempdb..#dd') is not null
select 'yes'
else
select 'no'

已测试!
ghosthjt 2004-04-30
  • 打赏
  • 举报
回复
临时表只存在于tempdb中不存在于其它数据库
请测试:
use pubs
create table #tmp (aa int)
select * from sysobjects where id =object_id('#tmp')
use tempdb
select * from sysobjects where id =object_id('#tmp')
drop table #tmp
SassyBoy 2004-04-30
  • 打赏
  • 举报
回复
在SQL SERVER中,用select object_id('Tempdb..#TempTable')該語句可判斷一個臨時表是否已經建立。(已建立返回值為一個整數,未建立則返回Null值)

我們可在建立臨時表前先用以下語句判斷臨時表是否已存在,當已存在時就刪除該臨時表。
if not (select object_id('Tempdb..#TempTable')) is null drop table #TempTable
prcgolf 2004-04-30
  • 打赏
  • 举报
回复
IF (OBJECT_ID('TEMPDB..#') IS NOT NULL)
PRINT 'EXISTS'
ELSE
PRINT 'NOT EXISTS'

34,837

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧