Chris Lombardi
Chris Lombardi

Reputation: 891

Get database name of table using SQL Server

I have the following SQL query which is selecting all of the column names based on some search criteria, however; I want to get the database name as well. How would I do this?

I have not been able to accomplish this with a join as of now. I am not sure what the relationship is between sys.tables and sys.databases. Any guidance would be appreciated.

SELECT
    c.name  AS 'ColumnName',
    t.name AS 'TableName'
FROM 
    sys.columns c
JOIN 
    sys.tables t ON c.object_id = t.object_id
WHERE 
    c.name LIKE '%Broker%'
ORDER BY 
    TableName, ColumnName;

Thank you. I was able to accomplish my goal by using the below code with your guidance. For further clarity I added the schema.

SELECT      
    '[' + SCHEMA_NAME(schema_id) + ']' + '.' +  '[' + db_name() + ']' as "Database_Schema_Name",
    t.name AS 'Table_Name',
    c.name  AS 'Column_Name'
FROM        
    sys.columns c
JOIN
    sys.tables t ON c.object_id = t.object_id
WHERE       
    c.name LIKE '%Broker%'
ORDER BY    
    Table_Name, Column_Name

Upvotes: 1

Views: 11556

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269445

In SQL Server, the system tables are stored per database. Hence, all is in one database, so you can just use dbname():

SELECT db_name() as DatabaseName, c.name AS ColumnName, t.name AS TableName
FROM sys.columns c JOIN
     sys.tables t
     ON c.object_id = t.object_id
WHERE c.name LIKE '%Broker%'
ORDER BY TableName, ColumnName;

Note: Because INFORMATION_SCHEMA tables are standard across databases, I prefer to get metadata information from those tables when available. This also has the advantage that you only need INFORMATION_SCHEMA.COLUMNS, so no JOIN is (explicitly) necessary.

Upvotes: 2

Bibin Mathew
Bibin Mathew

Reputation: 465

You can use this

SELECT DB_NAME(3)AS [Database Name]; 

Upvotes: 0

Related Questions