判斷sql表是否存在
1. sql語句 判斷表數據是否存在另一個表中
工具/材料:Management Studio。
1、首先在桌面上,點擊「Management Studio」圖標。
2. 鎬庝箞鍒ゆ柇sql鏁版嵁搴撴槸鍚﹀瓨鍦錛屽瓨鍦ㄥ垹闄
鍒ゆ柇鏁版嵁搴擄紝濡傛灉瀛樺湪鍒欏垹闄わ細
IF (EXISTS(SELECT * FROM master.dbo.sysdatabases WHERE dbid=db_ID('dbname')))
DROP DATABASE dbname
濡傛灉鎻愮ず錛氬垹闄ゆ暟鎹搴撴椂鎻愮ず鏁版嵁搴撴e湪琚浣跨敤錛屾棤娉曞垹闄(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 dbname
鎵╁睍璧勬枡
鍒ゆ柇鍌ㄥ瓨榪囩▼,濡傛灉瀛樺湪鍒欏垹闄
IF (EXISTS(SELECT * FROM sysobjects WHERE name='procerename' AND type='P'))
DROP PROCEDURE procerename
鍒ゆ柇瑙﹀彂鍣,濡傛灉瀛樺湪鍒欏垹闄
IF (EXISTS(SELECT * FROM sysobjects WHERE id=object_id(N'[dbo].[triggername]') AND OBJECTPROPERTY(id, N'IsTrigger') = 1))
DROP TRIGGER triggername
鍒ゆ柇鐢ㄦ埛鍑芥暟鏄鍚﹀瓨鍦,濡傛灉瀛樺湪鍒欏垹闄
姝ゅ則ype鏈変袱縐: '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
3. sql語句 判斷表是否存在
IF EXISTS(SELECT name FROM [sysobjects] WHERE name = '表名')
PRINT '該表存在'
ELSE
PRINT '該表不存在'。
4. sql 判斷一個表是否存在
用戶表在當前資料庫的系統表中,可使用以下語句進行查找:
select Name,ID from sysobjects where xtype='U'
若是將xtype='U'換成xtype='V'就可以查出來所有視圖
xtype參數大概有以下種類:
C = CHECK 約束
D = 默認值或 DEFAULT 約束
F = FOREIGN KEY 約束
FN = 標量函數
IF = 內嵌表函數
K = PRIMARY KEY 或 UNIQUE 約束
L = 日誌
P = 存儲過程
R = 規則
RF = 復制篩選存儲過程
S = 系統表
TF = 表函數
TR = 觸發器
U = 用戶表
V = 視圖
X = 擴展存儲過程