I wish do retrieve the database which contains table x, based on a column name I enter through e.g. My WHERE statement.
As of now, I run two seperate SELECT queries. Firstly, I search for which tables in the soloution contains a spesific column. Second, I have to manually search for all the resulting databases in the subquery.
I wish to have this dynamic, so that when entering the column name, both database and table are returned. Now, I get "NULL" the Database column.
I've managed to get the current db using only db_name, but that is not what I intend to do..
db_name(db_id(table1.name)) AS "Database" , table1.name AS 'Table', column1.name AS 'Column'
FROM sys.columns column1
JOIN sys.tables table1 ON column1.object_id = table1.object_id
WHERE column1.name LIKE 'columnname'
ORDER BY "Table", "Column"
(SELECT "db" FROM sys.databases WHERE CASE WHEN state_desc = 'ONLINE' THEN
OBJECT_ID(QUOTENAME("db") + '.[dbo].' + '[database1]', 'U')
END IS NOT NULL)
The code above is working wiithout errors. However, I do not manage to pull the Database name, and I can not understand how I could solve this.
I've used several earlier posts as reference to build up this code, as I'm a rookie to SQL.. :-)
Thanks in advance for any assitance. Br.