I have 6 variables that is: @SourceDatabase, @SourceSchema, @SourceTable, @TargetDatabase, @TargetSchema, @TargetTable
Im writing a query that should join values from INFORMATION_SCHEMA.COLUMNS.
Like this:
SELECT a.COLUMN_NAME, b.COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS a
LEFT OUTER JOIN INFORMATION_SCHEMA b
ON b.TABLE_SCHEMA = @SourceSchema
AND b.TABLE_NAME = @SourceTable
AND b.COLUMN_NAME = a.COLUMN_NAME
WHERE a.TABLE_SCHEMA = @TargetSchema
AND a.TABLE_NAME = @TargetTable
However, after I introduced the database-attributes, to do comparison cross databases, i just noticed that i dont think i can use the same query without making it dynamic as a String and putting databasename in front of INFORMATION_SCHEMA. Like DECLARE @SQL nvarchar(254) = 'SELECT * FROM ' + @SourceDatabase + '.INFORMATION_SCHEMA ...'. etc etc
Since im not really a fan of doing dynamic sql, im wondering if you guys have any clever solutions to do what im trying to do without going dynamic?
Dynamic SQL is certainly the easiest way to handle this kind of thing, but you are certain this is not an option?
The only other alternative I can think of is to UNION ALL on all of your databases, with an additional db name column:
The collation needs to be the same in both databases. But Dynamic SQL would be easier, and could be made to work for any database, rather than just those in your union list.