-
Dan Guzman 7,306 Reputation points
2021-02-18T13:06:56.6+00:00 Instead of the undocumented and unsupported
sp_MSforeachdb
procedure, consider building a batch withUSE
statements for each database and conditionally execute the query only when the table exists in the database.:CONNECT Server_A DECLARE @SQL nvarchar(MAX) = ( SELECT STRING_AGG(N'USE ' + QUOTENAME(name) + CAST(N'; IF OBJECT_ID(N''dbo.Fty'') IS NOT NULL BEGIN SELECT * FROM Fty WHERE name LIKE ''%Test%''; END ' AS nvarchar(MAX)),';') FROM sys.databases ); EXEC sp_executesql @SQL; GO
Pre-SQL Server 2017 where STRING_AGG is unavailable, use FOR XML for aggregate string concatenation:
DECLARE @SQL nvarchar(MAX) = STUFF(( SELECT N'; USE ' + QUOTENAME(name) + CAST(N'; IF OBJECT_ID(N''dbo.Fty'') IS NOT NULL BEGIN SELECT * FROM Fty WHERE name LIKE ''%Test%''; END' AS nvarchar(MAX)) FROM sys.databases FOR XML PATH(''), TYPE ).value('text()[1]', 'nvarchar(MAX)'),1,1,'') + ';'; EXEC sp_executesql @SQL; GO
Hi @Mike ,
Please refer to:
DECLARE @command varchar(1000)
SELECT @command = 'USE ? SELECT * FROM Fty where name like ''%Test%'' '
EXEC sp_MSforeachdb @command
Regards
Echo
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.