Sql server 如何使用单个查询检查多个表的存在性
目前我正在使用:Sql server 如何使用单个查询检查多个表的存在性,sql-server,Sql Server,目前我正在使用: select * from sys.tables where name = 'table name' 但是由于有很多表,所以需要很长时间,我必须逐一检查每个表。您可以尝试在类似中使用 select * from sys.tables where name IN ('tablename1','tablename2',...) 或者你可以试试看 SELECT 1 FROM systable INNER JOIN sysuserperm ON systable.cr
select *
from sys.tables
where name = 'table name'
但是由于有很多表,所以需要很长时间,我必须逐一检查每个表。您可以尝试在类似中使用
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
你可以试着用在类似的地方
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
一旦你能使用它:
USE DbName
SELECT *
FROM information_schema.tables
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME IN ('tb01','tbl02',...)
一旦你能使用它:
USE DbName
SELECT *
FROM information_schema.tables
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME IN ('tb01','tbl02',...)
如果要检查表名列表,请将其放入表变量中,并使用类似于以下代码的代码:
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;
上述方法可以很容易地扩展到多种对象。您可以将
信息\u SCHEMA.TABLES
替换为sys.all\u objects
,并相应地修改架构名称比较。如果要检查表名列表,请将其放入表变量中,并使用类似于以下代码的代码:
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;
上述方法可以很容易地扩展到多种对象。您可以将信息\u SCHEMA.TABLES
替换为sys.all\u objects
,并相应地修改架构名称比较