sqlserver 各种判断是否存在(表、视图、函数、存储过程等)
1、判断表是否存在
select * from sysobjects where id = object_id(表名) and OBJECTPROPERTY(id, N'IsUserTable') = 1
2、判断视图是否存在
select table_name from information_schema.views where table_name = 视图名
或者
SELECT * FROM dbo.sysobjects WHERE id = object_id('视图名') AND OBJECTPROPERTY(id, N'IsView') = 1
3、判断函数是否存在
select * from sysobjects where xtype='fn' and name='函数名'
或者
select * from dbo.sysobjects where id = object_id(N'[dbo].[函数名]') and xtype in (N'FN', N'IF', N'TF')
4、判断字段是否存在
select 1 from syscolumns where id=object_id('表名') and name='字段名'
5、判断索引是否存在
-
if not exists(select * from sysindexes where id=object_id('表名') and name='索引名')
-
create nonclustered index [索引名] on [表名](字段 asc,字段 asc)
-
go
6、判断存储过程是否存在
-
IF exists(SELECT * FROM sysobjects WHERE id=object_id(N'[master].[存储过程名称]') and xtype='P')
-
begin
-
drop procedure [master].[存储过程名称]
-
End
-
GO
-- SQL SERVER 判断是否存在某个触发器、储存过程
-- 判断储存过程,如果存在则删除
IF (EXISTS(SELECT * FROM sysobjects WHERE name='procedurename' AND type='P'))
DROP PROCEDURE procedurename-- 判断触发器,如果存在则删除
IF (EXISTS(SELECT * FROM sysobjects WHERE id=object_id(N'[dbo].[triggername]') AND OBJECTPROPERTY(id, N'IsTrigger') = 1))
DROP TRIGGER triggername-- 判断用户函数是否存在,如果存在则删除
-- 此处type有两种: 'TF'- Table-Value Function 表值函数 'FN'- Scalar-Value Function 标量值函数
IF (EXISTS(SELECT * FROM sysobjects WHERE id=object_id(N'[dbo].[userfunction]') AND (type='FN' OR type='TF')))
DROP FUNCTION userfunction
-- 判断视图是否存在,存在则删除
IF (EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME=N'viewname'))
DROP VIEW viewname
-- 判断用户表 是否存在,若存在则删除
IF (EXISTS(SELECT * FROM sysobjects WHERE id=N'tablename' AND OBJECTPROPERTY(id, N'IsUserTable')=1))
DROP TABLE tablename-- 判断数据库,如果存在则删除
IF (EXISTS(SELECT * FROM master.dbo.sysdatabases WHERE dbid=db_ID('dbname')))
DROP DATABASE dbname
-- 如果提示:删除数据库时提示数据库正在被使用,无法删除(Cannot drop database databasename because it is currently in use),使用:IF (EXISTS(SELECT * FROM master.dbo.sysdatabases WHERE dbid=db_ID('dbname')))
BEGIN
USE master
ALTER DATABASE dbname
SET single_user
WITH ROLLBACK IMMEDIATE
DROP DATABASE dbnameEND