gpt4 book ai didi

sql - sp_MSforeachdb : only include results from databases with results

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

我正在使用一个简单的命令运行以下存储过程sp_MSforeachdb。我的问题是如何限制结果仅显示至少有 1 条记录满足命令的数据库:

Sample of the result

这是我的存储过程:

EXECUTE master.sys.sp_MSforeachdb 'USE [?]; 

IF (EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = ''Tabs''))
BEGIN

SELECT ''?'' as dbname,T.TabName, T.TabPath
FROM Tabs T
WHERE T.TabID IN (

SELECT Distinct TM.TabID
FROM TabModules TM
WHERE mID IN (
...
)

)
ORDER BY T.TabName
END
'

有什么想法可以修改 sp,使其不显示具有空结果的数据库(参见图片)?

最佳答案

首先,停止使用 sp_MSforEachDb。哦,问题(如果你想要证据,请参阅 here )。

怎么样:

DECLARE @cmd NVARCHAR(MAX) = N'', @sql NVARCHAR(MAX) = N'';

SELECT @cmd += N'IF EXISTS (SELECT 1 FROM '
+ QUOTENAME(name) + '.sys.tables WHERE name = N''Tabs'')
SET @sql += N''UNION ALL
SELECT ''''' + name + ''''',T.TabName
FROM ' + QUOTENAME(name) + '.dbo.Tabs AS T
WHERE EXISTS
(
SELECT 1 FROM ' + QUOTENAME(name) + '.dbo.TabModules AS TM
WHERE TM.TabID = T.TabID
AND TM.mID IN -- this should probably be exists too
(
...
)
)
'''
FROM sys.databases
WHERE state = 0 -- assume you only want online databases
AND database_id > 4; -- assume you don't want system dbs

EXEC sp_executesql @cmd, N'@sql NVARCHAR(MAX) OUTPUT', @sql OUTPUT;

SET @sql = STUFF(@sql, 1, 10, '') + N' ORDER BY TabName;';

PRINT @sql; -- this will appear truncated, but trust me, it is not truncated
-- EXEC sp_executesql @sql;

如果您确实想要一些未知的、任意数量的单独结果集,则更改很简单。

DECLARE @cmd NVARCHAR(MAX) = N'', @sql NVARCHAR(MAX) = N'';

SELECT @cmd += N'IF EXISTS (SELECT 1 FROM '
+ QUOTENAME(name) + '.sys.tables WHERE name = N''Tabs'')
SET @sql += N''SELECT ''''' + name + ''''',T.TabName
FROM ' + QUOTENAME(name) + '.dbo.Tabs AS T
WHERE EXISTS
(
SELECT 1 FROM ' + QUOTENAME(name) + '.dbo.TabModules AS TM
WHERE TM.TabID = T.TabID
AND TM.mID IN -- this should probably be exists too
(
...
)
)
ORDER BY T.TabName;
'';'
FROM sys.databases
WHERE state = 0 -- assume you only want online databases
--AND database_id > 4; -- assume you don't want system dbs

EXEC sp_executesql @cmd, N'@sql NVARCHAR(MAX) OUTPUT', @sql OUTPUT;

PRINT @sql; -- this will appear truncated, but trust me, it is not truncated
-- EXEC sp_executesql @sql;

关于sql - sp_MSforeachdb : only include results from databases with results,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20131930/

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