SQL Server中判断表或者数据库是否存在的方法

数据库

法(一):

select * from master.dbo.sysdatabases where name='数据库名'

法(二):

if DB_ID('testdb') is not null -- 如果这个数据库已经存在了

drop database testdb;

create database testdb;

  

表对象

if OBJECT_ID('dbo.user','u') is not null
drop table dbo.user;
create table dbo.user(......);

 

select count(*) from sysobjects where id = object_id('数据库名.dbo.表名')

if exists (select count(*) from sysobjects where id = object_id('数据库名.dbo.表名'))

print '存在'

else

print '不存在' 表中字段

 

if exists(select * from syscolumns where name='colname1' and id=object_id('数据库名.dbo.表名'))

print '存在'

else

print '不存在'(代表表tablename1中存在colname1字段 )

例:select * from syscolumns where name='Test' and id=object_id('dbo.test') 存储过程或视图

if object_id('视图或存储过程名') is not null

drop proc/view 。。。    go

create proc/view 。。。

if Exists(select * from sysobjects where name='视图或存储过程名' AND type = 'P/V')

drop proc/view 。。。   go   create proc/view 。。。 

posted @ 2020-07-24 10:17  ittalk  阅读(911)  评论(0)    收藏  举报