0

I need to get database name from table names in SQL Server. I can query 'tablenames' in the database, but how do I get the database name for each table as well?

select * 
from sys.tables;

Output:

name    object_id   principal_id    schema_id   parent_object_id    type    type_desc   create_date modify_date is_ms_shipped   is_published    is_schema_published lob_data_space_id   filestream_data_space_id    max_column_id_used  lock_on_bulk_load   uses_ansi_nulls is_replicated   has_replication_filter  is_merge_published  is_sync_tran_subscribed has_unchecked_assembly_data text_in_row_limit   large_value_types_out_of_row    is_tracked_by_cdc   lock_escalation lock_escalation_desc    is_filetable    is_memory_optimized durability  durability_desc temporal_type   temporal_type_desc  history_table_id    is_remote_data_archive_enabled  is_external
DL_CONLog   719055  NULL    1   0   U   USER_TABLE  43:24.3 01:41.0 0   0   0   0   NULL    10  0   1   0   0   0   0   0   0   0   0   0   TABLE   0   0   0   SCHEMA_AND_DATA 0   NON_TEMPORAL_TABLE  NULL    0   0
DL_TIMJobImportLinkBrokerToModule   771110  NULL    1   0   U   USER_TABLE  45:12.1 45:20.7 0   0   0   1   NULL    64  0   1   0   0   0   0   0   0   0   0   0   TABLE   0   0   0   SCHEMA_AND_DATA 0   NON_TEMPORAL_TABLE  NULL    0   0
3
  • Please show us what is being used to get the 'tablenames'. Server name is usually part of the connection string. Commented Jun 11, 2019 at 0:56
  • If you can query the table names, you're already connected to the database, so you know what the database name is already. How else would you ask it for the list of table names? Commented Jun 11, 2019 at 0:58
  • I have edited my question., I guess sys.tables keep the information for all tables across databases. Commented Jun 11, 2019 at 1:32

2 Answers 2

1

Try using

SELECT * FROM  INFORMATION_SCHEMA.TABLES
Sign up to request clarification or add additional context in comments.

Comments

0

sys.tables gives you list of table of current database. The current database name can be query from db_name().

If you are looking for a list of tables of a specific database, use db1.sys.tables

Not really sure what is your requirement, but if you want current database & table name, you can query INFORMATION_SCHEMA.TABLES

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.