sql server判斷表存在


在創建表、更改表結構、刪除表或對表進行什么操作之前,一個比較嚴謹的做法是先判斷該表是否已經存在。

在SQL Server中判斷一個表是否存在,有兩個方法,下面以diso表為例。

方法1

if exists(select top 1 1 from sysObjects where id = object_id(N'diso') and xtype = 'U')
    print '表diso存在'
else 
    print '表diso不存在'

原理是查詢【sysObjects】這張系統表,該表保存了所有對象信息,既然是所有對象,自然包括表的信息,其中xtype為【U表示為用戶表。

方法2

if object_id(N'diso', N'U') is not null
    print '表diso存在'
else 
    print '表diso不存在'

臨時表

前面都是判斷普通表,如果是判斷臨時表的話,則需要在臨時表前加上【tempdb..】前綴,指明這是一個臨時表。

if exists(select top 1 1 from sysObjects where id = object_id(N'tempdb..#diso') and xtype = 'U')
    print '表#diso存在'
else 
    print '表#diso不存在'
if object_id(N'tempdb..#diso', N'U') is not null
    print '表diso存在'
else 
    print '表diso不存在'

臨時表實際上還是一個表,只不過查詢的時候和實體表還是有點區別。

 

"去走自己的路,贏要贏得理所當然,輸也要輸得清清楚楚。"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM