1

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
0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use this

SELECT DB_NAME(3)AS [Database Name]; 

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.