如何使用单个查询检查多个表的存在

时间:2015-12-24 05:43:26

标签: sql-server

目前我正在使用:

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

但由于有很多桌子需要很长时间,我必须逐一检查每一张桌子。

3 个答案:

答案 0 :(得分:0)

您可以尝试使用IN

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

答案 1 :(得分:0)

一旦可以使用:

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

答案 2 :(得分: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;

上述方法可以很容易地扩展到多种对象。您可以将INFORMATION_SCHEMA.TABLES替换为sys.all_objects,并相应地修改架构名称比较。