码迷,mamicode.com
首页 > 数据库 > 详细

SQL SERVER数据库判断对象是否存在的方法汇总

时间:2015-02-25 18:38:45      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:sql server

--库是否存在
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_约束名]

 

SQL SERVER数据库判断对象是否存在的方法汇总

标签:sql server

原文地址:http://blog.csdn.net/waterxcfg304/article/details/43447329

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!