SQL語句判斷資料庫、表、欄位是否存在
阿新 • • 發佈:2019-02-09
一、資料庫
(1)查詢系統中-->存放所有資料庫資訊的資訊表(sysdatabases)
語句:
select * from master.dbo.sysdatabases
where name='databasename'
①返回rs(有關於這個資料庫的所有資訊,返回值是資料庫結果集) java程式中執行一下 rs.next()便可。
②資料庫可以子查詢一下 if(.....) is not null
(2)if db_id('databasename') is not null
drop database
go
create
(3)exec sp_hlepdb databasename
二、表
(1)select count(*) from sysobjects where id = object_id('資料庫名.Owner.表名')
if exists(select count(*) from sysobjects where id = object_id('資料庫名.Owner.表名'))
print '存在'
else
print '不存在'
三、欄位
if exists (select * from syscolumns where name='colname1' and id=object_id('資料庫名.Owner.表名'))
print '存在'
else
print '不存在'
(代表表tablename1中存在colname1欄位 )
例:
select * from syscolumns where name='Test' and id=object_id('dbo.test')