SQL SERVER資料庫判斷對象是否存在的方法匯總,sqlserver
--庫是否存在
if exists(select * from master..sysdatabases where name=N'')
print 'exists'
else
print 'not exists'
-- 判斷要建立的表名是否存在,存在就刪除
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[表名]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
-- 刪除表
drop table [dbo].[表名]
GO
--判斷一個表的列是否存在
IF COL_LENGTH( '表名','列名') IS NULL
PRINT 'not exists'
ELSE
PRINT 'exists'
alter table 表名 drop constraint 預設值名稱
go
alter table 表名 drop column 列名
go
--判斷要建立暫存資料表是否存在
If Object_Id('Tempdb.dbo.#Test') Is Not Null
Begin
print '存在'
End
Else
Begin
print '不存在'
End
-- 判斷要建立的預存程序名是否存在
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[預存程序名]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
-- 刪除預存程序
drop procedure [dbo].[預存程序名]
GO
-- 判斷要建立的視圖名是否存在
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[視圖名]') and OBJECTPROPERTY(id, N'IsView') = 1)
-- 刪除視圖
drop view [dbo].[視圖名]
GO
-- 判斷要建立的函數名是否存在
if exists (select * from sysobjects where xtype='fn' and name='函數名')
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[函數名]') and xtype in (N'FN', N'IF', N'TF'))
-- 刪除函數
drop function [dbo].[函數名]
GO
/*
if col_length('表名', '列名') is null
print '不存在'
select 1 from sysobjects where id in (select id from syscolumns where name='列名') and name='表名'
*/
if col_length('BIU8_GL_ACCVOUCH', 'iperiod') is null
print '不存在'
select 1 from sysobjects where id in (select id from syscolumns where name='iperiod') and name='BIU8_GL_ACCVOUCH'
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[CK_約束名]') AND parent_object_id = OBJECT_ID(N'[dbo].[表名]'))
ALTER TABLE [dbo].[表名] DROP CONSTRAINT [CK_約束名]