首页
/
每日頭條
/
科技
/
數據庫分類彙總sql語句
數據庫分類彙總sql語句
更新时间:2026-01-26 23:29:51

經常寫SQL腳本的朋友,對if exists肯定非常熟悉,在做删除或更新操作之前,為了保證我們的操作的有效性避免異常的發生,我們習慣于先用if exists做一下判斷。

數據庫分類彙總sql語句(數據庫大師成長日記)1

今天我們就把if exists的各種常用的應用場景做一個總結。

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、判斷視圖是否存在

--SQL Server 2000 IF EXISTS (SELECT * FROM sysviews WHERE object_id = '[dbo].[視圖名]' --SQL Server 2005及之後 IF EXISTS (SELECT * FROM sys.views WHERE object_id = '[dbo].[視圖名]'

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、判斷列是否存在

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

8、判斷列是否自增列

if columnproperty(object_id('table'),'col','IsIdentity')=1 print '自增列' else print '非自增列'

9、判斷表中是否存在索引

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

希望對您有所幫助!

,
Comments
Welcome to tft每日頭條 comments! Please keep conversations courteous and on-topic. To fosterproductive and respectful conversations, you may see comments from our Community Managers.
Sign up to post
Sort by
Show More Comments
Copyright 2023-2026 - www.tftnews.com All Rights Reserved