Friday, May 8, 2015

Run a query in Multiple Databases - SQL

we can use a inbuilt Stored procedure called 'sp_MSforeachdb' for querying multiple DBs.

this is a SP which run on all databases in currunt SQL Server insance.

ex:

declare @command varchar(100)
set @command='select ''?'''
exec sp_MSforeachdb @command

and this code will return all DB names as follows
























you can get this result sets to a single table using table variable as follows


declare @t table (dbname varchar(100))
declare @command varchar(100)
set @command='select ''?'''

insert into @t
exec sp_MSforeachdb @command
select * from @t























ans also you can get details of your preferred databases only


declare @t table (DBname varchar(50),TotalObjects varchar(max))
DECLARE @command varchar(max)

SELECT @command = 'IF ''?'' IN(''ExcelineDev'',''ReportServer$SQL2012'',''TestDB1''
) BEGIN USE ?
EXEC
(''
select DB_NAME(DB_ID()), count(*) as TotalObjects from [?].dbo.sysobjects
'')
END'

insert into @t
EXEC sp_MSforeachdb @command
select * from @t
























hope this would help

No comments:

Post a Comment