How do I list all tables with their respective databases?

Asked

Viewed 16,830 times

6

I would like to list all the tables in my database that ends with a specific name and also all my databases that match these tables. I tried to do it but nothing comes back.

Query

SELECT da.name AS BANCOS,ta.name as TABELAS
FROM sys.schemas da join  sys.tables ta
on da.schema_id = ta.schema_id
where ta.name like '%attach'
group by da.name, ta.name
  • Kelvin, I’ve made an issue of your question which I think has become more readable, could you tell me from my edition if this is what you want? I say it because if it’s not I’ll come back with the question the way it was!

  • Thanks Marconi is just what I wanted to ask :)

  • What a problem in :)

  • I’m already days trying to find a solution and I can’t find a way out...

  • 1

    Kevin, The @Rodolpho Sa response worked for me. I think that’s what you want

5 answers

6


The following query:

DECLARE @tabelas TABLE(nome_database SYSNAME,
                       nome_schema   SYSNAME,
                       nome_tabela   SYSNAME);
DECLARE @database SYSNAME;

SET NOCOUNT ON;

DECLARE bases CURSOR LOCAL FAST_FORWARD FOR
  SELECT d.name
    FROM sys.databases d;
OPEN bases
FETCH NEXT FROM bases INTO @database
WHILE @@FETCH_STATUS = 0
BEGIN
  INSERT INTO @tabelas(nome_database,
                       nome_schema,
                       nome_tabela)
  EXEC('SELECT ''' + @database + ''',
               s.name,
               t.name
          FROM ' + @database + '.sys.tables t
               INNER JOIN ' + @database + '.sys.schemas s ON s.schema_id = t.schema_id
         WHERE t.name LIKE ''%cliente''');

  FETCH NEXT FROM bases INTO @database;
END;
CLOSE bases;
DEALLOCATE bases;

SELECT *
  FROM @tabelas;

-- Resumo
SELECT nome_database,
       count(1) AS quantidade
  FROM @tabelas t
 GROUP BY nome_database;
  • Uses the table sys.database to traverse in a cursor;
  • Mounts a query dynamics using the tables sys.tables and sys.schemas in syntax [NOME DA DATABASE].[NOME DO SCHEMA].[NOME DA TABELA];
  • Insert into a variable table in the formed nome_database, nome_schema and nome_tabela.
  • At the end of the query with group by shows the amount of tables that corresponds to the filter by database;
  • 1

    Sorack this is the best answer and returned even the tables that end with "ATTACH". Thank you very much :)

  • You said that to build a dynamic query should use "sys.table, sys.schemas ect" I was left with a question in this script that you passed.At the moment I want to know the row total of each table using "ROWS" as I will then pass this Rows in declare?

  • 1

    In fact this answer is more complete than mine. Congratulations @Sorack !

  • got it. Because in this case I wanted to list all the databases with all the tables with specific names that end with "ATTACH" and at the end list the row total of each bank.I managed to do but getting a little out of the way you did.only that the only problem is that it returns everything as if it were many tables.while I want to join all in one table only.

  • here an example if you can take a look.I tried a UNION but nothing. EXEC sp_msforeachdb 'select'? 'AS "Banks", s.name, t.name AS "TABLES",max(si.Rows) as "Column Number" from [?].sys.Tables t Inner Join [?].sys.schemas on t.schema_id = s.schema_id Inner Join [?].sys.Partitions si on t.object_id = si.object_id Wt.name like "%HERE" group by s.name,t. name'

  • I just saw it and went to test it and follow it step by step to understand it. I appreciate the sacrifice you’re making, making yourself available to help me, and I appreciate that. this part here: select * from @tables; select name_database Count(1) as quantity from @tables t group by name_database; lists the databases and row totals but wanted the rows of each table

  • ai I switched to : select tableName, Count(1) the quantity from @tables t group by tableName;so the quantity returns all 1.I think I should use max() but when I pass max(Rows) I get an error in the Rows I passed as parameter. Sorry to intrude and waste your time but I need help...

  • "At the end the query with group by shows the number of tables that corresponds to the filter per database;"All right @Sorack thanks for everything but thought maybe I didn’t explain well.If you could just show how to show the amount of rows (which is what I asked for) that matches the table filter I’ll be grateful friend. That’s all I need to do.

Show 3 more comments

4

I believe you can use something like this:

declare @BaseName varchar(100);
Declare @SelectTables varchar(1000);
--Primeiro obtenho em um cursor a lista dos banco de dados existentes
declare C_bases cursor for SELECT name FROM sys.databases;

--Abre o curosr
open C_bases;
-- Posiciona o cursor na primeira linha
FETCH NEXT FROM C_bases INTO @BaseName

-- Enquanto ainda tem linhas no cursor
WHILE @@FETCH_STATUS = 0  
BEGIN  

    --Imprimo o nome do banco 
    print @BaseName

    -- Monto o comando SQL que obtém a lista de tabelas da base onde o cursor esta posicionado
    -- Ex.: Na query abaixo eu listo as tabelas do banco [master] 
    -- SELECT * FROM [master].INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'
    set @SelectTables = 'SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME  FROM [' + @BaseName+  '].INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ''BASE TABLE''';
    -- Executa o comando SQL gerado
    execute (@SelectTables);


  -- Posiciona o cursor na próxima linha ( ou próxima base no caso)
  FETCH NEXT FROM C_bases INTO @BaseName 
END   

--Fecha o cursor
CLOSE C_bases;  
--Desaloca o curosr
DEALLOCATE C_bases; 

Abs.

  • In my opinion this is the correct answer, just needed to add AND TABLE_NAME like '%attach'. Could you explain that answer @Rodolpho?

  • I don’t understand what each line does...?

  • Of course. The INFORMATION_SCHEMA.TABLES lists the database tables where the query is being executed. So I looped in sys.databases to take the base name and dynamically mount select and thus get the information INFORMATION_SCHEMA.TABLES from other database, for example: SELECT * FROM [master].INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' .

  • I’ll edit my reply and post some comments there.

  • @Rodolphosa edict your reply and adds the information please

  • Done! If you need anything else, just let me know.

  • 1

    @Rodolphosa sensatsional your answer, got very good this Query. I just found it very complex. + 1

  • 1

    Hehehe Valeu @Rodolpho your answer is just that. With the comments it helped me a little to understand but it’s very complex.Still thanks to everyone to be able to try to help me. you guys are awesome!

Show 3 more comments

2

I finally managed to solve this problem I had. I found a specific solution to what I was looking for.I decided to post it here, because I think it might help someone else who might need it someday. :)

DECLARE @banco_nome nvarchar(MAX), @tabela_nome nvarchar(MAX)

DECLARE @banco_cursor CURSOR  
DECLARE @sqlstatement nvarchar(MAX)
DECLARE @count_sql nvarchar(MAX)
DECLARE @total int

DECLARE @RegistrosFotograficos TABLE
(
  DatabaseName nvarchar(max),
  TableName nvarchar(max),
  Total int
)

SET @banco_cursor = CURSOR FORWARD_ONLY FOR
    SELECT name FROM sys.databases

OPEN @banco_cursor
FETCH NEXT FROM @banco_cursor INTO @banco_nome
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @sqlstatement = 'DECLARE tabela_cursor CURSOR FORWARD_ONLY FOR SELECT TABLE_NAME FROM ' + @banco_nome + '.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ''BASE TABLE'' AND TABLE_NAME LIKE ''%ATTACH'' ORDER BY TABLE_NAME'
    EXEC sp_executesql @sqlstatement

    OPEN tabela_cursor
    FETCH NEXT FROM tabela_cursor INTO @tabela_nome
    WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @count_sql = 'USE ' + @banco_nome + '; SELECT @total=COUNT(1) FROM ' + @tabela_nome;
        EXECUTE sp_executesql @count_sql, N'@total int OUTPUT', @total=@total OUTPUT

        INSERT INTO @RegistrosFotograficos (DatabaseName, TableName, Total) VALUES (@banco_nome, @tabela_nome, @total);

        FETCH NEXT FROM tabela_cursor INTO @tabela_nome
    END
    CLOSE tabela_cursor;
    DEALLOCATE tabela_cursor;

    FETCH NEXT FROM @banco_cursor INTO @banco_nome
END
CLOSE @banco_cursor;
DEALLOCATE @banco_cursor;

SELECT * FROM @RegistrosFotograficos

-1

A solution to show which database is the searched table:

SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '%attach'

That might help you too:

SELECT *
FROM sysobjects sobjects
WHERE sobjects.xtype = 'U' and  sobjects.name like '%attach' 

The following is a list of xtype

AF: Aggregate function (CLR) 
C: CHECK constraint 
D: Default or DEFAULT constraint 
F: FOREIGN KEY constraint 
L: Log FN: Scalar function 
FS: Assembly (CLR) scalar-function 
FT: Assembly (CLR) table-valued function 
IF: In-lined table-function 
IT: Internal table 
P: Stored procedure 
PC: Assembly (CLR) stored-procedure 
PK: PRIMARY KEY constraint (type is K) 
RF: Replication filter stored procedure 
S: System table SN: Synonym SQ: Service queue 
TA: Assembly (CLR) DML trigger 
TF: Table function 
TR: SQL DML Trigger 
TT: Table type 
U: User table 
UQ: UNIQUE constraint (type is K) 
V: View 
X: Extended stored procedure
  • I don’t think that’s it! He wants to know which tables end with attachand on which banks are these tables.

  • I’ve adjusted the code

  • 1

    It doesn’t work. The table INFORMATION_SCHEMA.TABLES only show of database selected

  • Unfortunately that’s not what Luiz is looking for. I think my question was not clear.I want to list all the tables that belong to all the databases of my sql.I just want the names of the banks that with the respective tables that end with "ATTACH" I do not know if so was clearer.

-1

Try something like:

SELECT * FROM sys.databases as db
INNER JOIN INFORMATION_SCHEMA.TABLES as tb ON db.name=tb.TABLE_CATALOG AND TABLE_NAME like '%attach'
  • INFORMATION_SCHEMA.TABLES only shows the tables from where the query is running and not from all existing databases in the installation. Otherwise your query would be perfect.

  • 1

    It doesn’t work. The table INFORMATION_SCHEMA.TABLES only show of database selected

  • Unfortunately, that didn’t work for me. What I want to do is actually list all the tables of each database that I have in my sql.so there is no way to use "use databse" because it is not a check for a database but for all at once. But thanks for answering Eder :)

  • I forgot to mention SQL SERVER 2008 R2

  • The query you passed works but in this case I have to use "USE myDataBase" and returns only the result of this selected database. I wonder if there’s a way to return to all my banks at once?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.