SQLServer 查詢某張表是否存在於數據庫
本查詢在SqlServer 2016 上均執行成功
此例中數據庫爲testdb1,testdb2,表名爲TestTable
查詢
declare @tablename as varchar(64)
set @tablename = ‘TestTable’
select
case when exists(select * from testdb1.sys.tables where name = @tablename) then ‘Existence’ end as ‘testdb1’,
case when exists(select * from testdb2.sys.tables where name = @tablename) then ‘Existence’ end as ‘testdb2’;
若查詢多個庫,則直接在後面追加:case when exists(select * from testdb.sys.tables where name = @tablename) then ‘Existence’ end as ‘testdb’;即可。
結果
testdb1 | testdb2 |
---|---|
Existence | NULL |