2015-12-24 20 views
1

目前我使用檢查多個表的存在:如何使用單個查詢

select * 
from sys.tables 
where name = 'table name' 

但它是需要長時間,因爲有很多的表,我要檢查他們每個人一個接一個。

回答

0

您可以嘗試使用像

select * from sys.tables where name IN ('tablename1','tablename2',...) 

,或者你可以改爲嘗試

SELECT 1 
FROM systable INNER JOIN sysuserperm ON systable.creator = sysuserperm.user_id 
WHERE sysuserperm.user_name = 'yourusername' AND 
     systable.table_type = 'BASE' AND 
     systable.table_name IN ('tablename1', 'tablename2') 
GROUP BY sysuserperm.user_name, systable.table_type 
0

一旦可以使用這樣的:如果你有表名的列表

USE DbName 
SELECT * 
FROM information_schema.tables 
WHERE TABLE_TYPE = 'BASE TABLE' 
     AND TABLE_NAME IN ('tb01','tbl02',...) 
0

檢查,將其放入一個表變量,並使用類似於下面的代碼:

declare @t table (
    SchemaName sysname not null, 
    ObjectName sysname not null, 
    primary key (ObjectName, SchemaName) 
); 

-- Populate this with your data 
insert into @t (SchemaName, ObjectName) 
values 
    (N'dbo', N'SomeTable1'), 
    (N'dbo', N'AnotherTable2'), 
    (N'abc', N'DEF'); 

if exists (
    select 0 from @t t 
     left join INFORMATION_SCHEMA.TABLES xt on xt.TABLE_SCHEMA = t.SchemaName 
      and xt.TABLE_NAME = t.ObjectName 
    where xt.TABLE_NAME is null 
    ) 
    select concat(t.SchemaName, N'.', t.ObjectName) as [MissingObject] 
    from @t t 
     left join INFORMATION_SCHEMA.TABLES xt on xt.TABLE_SCHEMA = t.SchemaName 
      and xt.TABLE_NAME = t.ObjectName 
    where xt.TABLE_NAME is null; 

上述方法可以很容易地擴展爲多種對象。您可以用sys.all_objects替換INFORMATION_SCHEMA.TABLES並相應地修改模式名稱比較。