gpt4 book ai didi

sql - 查找具有特定表的数据库或在 SQL Server 的每个数据库中查找表

转载 作者:行者123 更新时间:2023-12-02 08:04:58 26 4
gpt4 key购买 nike

我有一个包含数百个数据库的 SQL Server,每个数据库都有数百个表。现在我想在这些数据库中找到我要查找的表。

我可以使用

查找单个数据库中是否存在表
use myDatabase 
select * from sys.tables where name = 'mytable'
GO

但是使用这个意味着我必须手动更改数据库数百次。我只想查找数据库名称。有出路吗?

最佳答案

好吧,如果您只想查找包含特定表的每个数据库,并且不打算查询该表,那么您可以这样做:

create table #t (
DBName sysname not null
)
go
exec sp_MSforeachdb 'use [?]; if OBJECT_ID(''dbo.mytable'') is not null insert into #t (DBName) select ''?'''
go
select * from #t
go
drop table #t

(如果您没有在数据库中使用多个架构,则无需在 OBJECT_ID 调用中指定 dbo,否则我使用它来避免在错误架构中查找表)

关于sql - 查找具有特定表的数据库或在 SQL Server 的每个数据库中查找表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4733170/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com