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 。。。 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM