question

pedrink avatar image
pedrink asked

How to list the data from a table in all databases

I need a cursor inside a procedure where the user specifies a Table name and the cursor search this table in all databases. If the table exists, it shows the data from the table, if it doesn't exists, it prints out "that table doesn't exists".

CREATE PROCEDURE sp_Teste @nomeTabela varchar(50)='T2'
AS


DECLARE 
@TableName		VARCHAR(30),
@databasename           VARCHAR(30),
@cmd			VARCHAR (MAX),
--@qtd                    numeric(3,0)


--declare @perfil            varchar(100);
--declare @email             varchar(100);
--declare @sub               varchar(100);
declare @msg                 varchar(max);




create table	#T1 (dbname varchar(80))
insert into		#T1 (dbname) SELECT name FROM sys.databases WHERE name NOT IN ('master','tempdb','model','msdb')


set @qtd = (select COUNT(*) from #T1)




/*=================================CURSOR=================================*/


--Declare @UID int;


DECLARE db_cur CURSOR FOR
    select dbname from #T1 order by dbname;


	CREATE table #tempTB 
		(
			[nome] varchar(max),
			[idade] int,
			[salario] int
		)


OPEN db_cur


FETCH NEXT FROM db_cur INTO @databasename;
WHILE @@FETCH_STATUS = 0


BEGIN


    
			DECLARE tb_cur CURSOR FOR
				SELECT * FROM @nomeTabela 


			OPEN tb_cur;


			FETCH NEXT FROM tb_cur INTO @UID;
			WHILE @@FETCH_STATUS = 0


				BEGIN
							IF exists (select name from sys.tables where name = @nomeTabela) 


										BEGIN


													SET @CMD = 'SELECT * FROM '+ @nomeTabela 
													INSERT INTO #tempTB(nome, idade, salario) EXEC (@CMD)


										END




							IF not exists (select name from sys.tables where name = @nomeTabela) 


										BEGIN
													SET @msg = 'Nao existe a tabela ' + @nomeTabela
													PRINT @msg
										END   




							FETCH NEXT FROM tb_cur INTO @databasename;


				END




			CLOSE tb_cur;
			DEALLOCATE tb_cur;
			FETCH NEXT FROM db_cur INTO @databasename;




END;




CLOSE db_cur;
DEALLOCATE db_cur;

tablelisttsql mutiple databases
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
dbnerd3000 avatar image
dbnerd3000 answered

Here's an alternative to cursors which you may find useful, it uses an undocumented stored procedure.

Credit to these sites:
https://www.mssqltips.com/sqlservertip/1414/run-same-command-on-all-sql-server-databases-without-cursors/

https://stackoverflow.com/questions/39448776/select-query-from-all-databases-where-a-table-exists

DECLARE @SearchTable varchar(100)
DECLARE @command varchar(1000) 

SET @SearchTable = 'TestTable'
SELECT @command = ' use ?; if exists(select * from  information_schema.tables where table_name= ''' + @SearchTable + ''') begin select * from ' + @SearchTable + ' end ELSE BEGIN SELECT ''Table doesnt exist in ?'' END'

EXEC sp_MsForEachDb @command
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.