SQL Server判斷資料庫、表、儲存過程、函式是否存在
阿新 • • 發佈:2019-02-06
--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(N'函式名') IS NOT NULL DROP FUNCTION dnt_split ---5.判斷資料庫是否開啟了全文搜尋 SELECT DATABASEPROPERTY('資料庫名', 'isfulltextenabled') --6.判斷全文目錄是否存在 SELECT * FROM sysfulltextcatalogs WHERE NAME = '全文目錄名稱' --7.判斷要建立臨時表是否存在 IF OBJECT_ID('臨時表') IS NOT NULL BEGIN PRINT '存在' END ELSE BEGIN PRINT '不存在' END -- 8.判斷要建立的檢視名是否存在 IF EXISTS ( SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[檢視名]') AND OBJECTPROPERTY(id, N'IsView') = 1 ) DROP VIEW [dbo].[檢視名]
--9.判斷table1中是否存在name欄位 IF EXISTS( SELECT * FROM syscolumns WHERE id = OBJECT_ID('table1') AND NAME = 'name' ) BEGIN SELECT * FROM table1; END --10.判斷table1中是否存在name欄位且刪除欄位 IF EXISTS( SELECT * FROM syscolumns WHERE id = OBJECT_ID('table1') AND NAME = 'name' ) BEGIN SELECT * FROM table1; ALTER TABLE table1 DROP COLUMN NAME END