sp_MSforeachdb query help(sp_MSforeachdb 查询帮助)
问题描述
我正在使用许多相同的数据库,因此我使用 sp_MSforeachdb 过程以便我可以从表中检索信息.
I'm working with a lot of databases that are the same so I am using the sp_MSforeachdb procedure so that I can retrieve information from a table.
我遇到的问题是盒子上还有其他数据库没有表,所以我抛出了无效对象错误.
The problem I have encountered is that there are other databases on the box that don't have the table, so I'm throwing invalid object errors.
这是我目前所拥有的,我正在过滤 LoginDatabase,因为它具有相同的表,但我不希望在查询中使用它.
Here is What I have at the moment, I'm filtering LoginDatabase because it has the same table but I don't want that in the query.
我的问题是,我如何才能将其限制为包含我想从中获取信息的表的数据库.
My question is, how can I restrict it just to the databases with the table I want to get information back from.
SET NOCOUNT ON
CREATE TABLE #tmpData
(
DbName VARCHAR(30),
DbVersion FLOAT
)
exec sp_msforeachdb @command1='
USE ?;
INSERT INTO #tmpData
SELECT ''?'', (SELECT Setting
FROM ?.dbo.gl_SysParams
WHERE Keyword = ''DatabaseSchema'')
FROM sysobjects o
WHERE type=''U''
AND [name] = ''gl_SysParams''
AND ''?'' <> ''LoginDatabase'' ORDER BY [name]
'
SET NOCOUNT OFF
SELECT DbName, DbVersion FROM #tmpData ORDER BY DbName
DROP TABLE #tmpData
推荐答案
您可以在每个数据库中使用对 sp_MSforeachtable 的调用,您可以在其中使用 @WhereAnd 参数过滤到您感兴趣的表 - 它赢了'不存在于您不感兴趣的数据库中,因此 sp_MSforeachtable 将在其中运行 0 次,并在每个带有该表的数据库中运行 1 次.
You could use a call to sp_MSforeachtable within each database, where you use the @WhereAnd parameter to filter down to just the table you're interested in - it won't exist in the database you're not interested in, so sp_MSforeachtable will run 0 times in there, and 1 time in each database with the table.
编辑简单的例子只是在我的一个随机服务器上运行,我知道只有一个数据库有一个 tblClient 表,有一个 ClientID 列(请原谅命名):
Edit Simple example just run against a random server of mine, where I knew only one database had a tblClient table, with a ClientID column (forgive the naming):
create table #t (
ID int not null
)
exec sp_MSforeachdb 'use ? exec sp_MSforeachtable ''insert into #t(ID) select ClientID from ~'',''~'',@whereand=''and o.name=''''tblClient''''''','?'
select * from #t
drop table #t
这篇关于sp_MSforeachdb 查询帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:sp_MSforeachdb 查询帮助


基础教程推荐
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01