在创建表、更改表结构、删除表或对表进行什么操作之前,一个比较严谨的做法是先判断该表是否已经存在。

在SQL Server中判断一个表是否存在,有两个方法,下面以diso表为例。

方法1

if exists(select top 1 1 from sysObjects where id = object_id(N'diso') and xtype = 'U')
    print '表diso存在'
else 
    print '表diso不存在'

原理是查询【sysObjects】这张系统表,该表保存了所有对象信息,既然是所有对象,自然包括表的信息,其中xtype为【U表示为用户表。

方法2

if object_id(N'diso', N'U') is not null
    print '表diso存在'
else 
    print '表diso不存在'

临时表

前面都是判断普通表,如果是判断临时表的话,则需要在临时表前加上【tempdb..】前缀,指明这是一个临时表。

if exists(select top 1 1 from sysObjects where id = object_id(N'tempdb..#diso') and xtype = 'U')
    print '表#diso存在'
else 
    print '表#diso不存在'
if object_id(N'tempdb..#diso', N'U') is not null
    print '表diso存在'
else 
    print '表diso不存在'

临时表实际上还是一个表,只不过查询的时候和实体表还是有点区别。

 

"去走自己的路,赢要赢得理所当然,输也要输得清清楚楚。"

相关文章:

  • 2021-12-15
  • 2022-12-23
  • 2022-02-15
  • 2021-12-27
  • 2022-02-13
  • 2021-11-28
  • 2022-12-23
猜你喜欢
  • 2021-12-03
  • 2022-02-05
  • 2021-07-12
  • 2022-02-02
  • 2021-12-08
  • 2022-02-02
  • 2021-12-29
相关资源
相似解决方案