sql server判断数据库、表、列、视图是否存在

1 判断数据库是否存在

if exists (select * from sys.databases where name = ‘数据库名’)
drop database [数据库名]

2 判断表是否存在

if exists (select * from sysobjects where id = object_id(n'[表名]’) and objectproperty(id, n’isusertable’) = 1)
drop table [表名]

3 判断存储过程是否存在

if exists (select * from sysobjects where id = object_id(n'[存储过程名]’) and objectproperty(id, n’isprocedure’) = 1)
drop procedure [存储过程名]

4 判断临时表是否存在

if object_id(‘tempdb..#临时表名’) is not null
drop table #临时表名

5 判断视图是否存在

–判断是否存在’myview52’这个试图
if exists (select table_name from information_schema.views where table_name = n’myview52′)
print ‘存在’
else
print ‘不存在’

6 判断函数是否存在

— 判断要创建的函数名是否存在
if exists (select * from dbo.sysobjects where id = object_id(n'[dbo].[函数名]’) and xtype in (n’fn’, n’if’, n’tf’))
drop function [dbo].[函数名]

7 获取用户创建的对象信息

select [name],[id],crdate from sysobjects where xtype=’u’

8 判断列是否存在

if exists(select * from syscolumns where id=object_id(‘表名’) and name=’列名’)
alter table 表名 drop column 列名

9 判断列是否自增列

if columnproperty(object_id(‘table’),’col’,’isidentity’)=1
print ‘自增列’
else
print ‘不是自增列’

select * from sys.columns where object_id=object_id(‘表名’) and is_identity=1

10 判断表中是否存在索引

if exists(select * from sysindexes where id=object_id(‘表名’) and name=’索引名’)
print ‘存在’
else
print ‘不存在’

删除索引 drop index 表名.索引名

或: drop index 索引名 on 表名(貌似2000不行)

11 查看数据库中对象

select * from sys.sysobjects where name=’对象名’ select * from sys.sysobjects where name=’对象名’

(0)
上一篇 2022年3月22日
下一篇 2022年3月22日

相关推荐