承接国内外服务器租用托管、定制开发、网站代运营、网站seo优化托管接单、网站代更新,新老站点皆可!!咨询QQ:3787320601

sql server判断数据库、表、列、视图会不会存在

管理员 2023-07-14 08:01:28 互联网圈 0 ℃ 0 评论 2685字 收藏

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=’对象名’

文章来源:丸子建站

文章标题:sql server判断数据库、表、列、视图会不会存在

https://www.wanzijz.com/view/64239.html

X

截屏,微信识别二维码

微信号:weimawl

(点击微信号复制,添加好友)

打开微信