I have a situation where I need to get data from one of over 100 database (all with the exact same schema) depending on a parameter passed to a stored procedure.
The way I’ve been trying to do this is to build a dynamic SQL statement to execute with sp_executesql:
(This is just a test script BTW):
declare @sql nvarchar(1000)
set @sql = 'select top 10 * from [SERVER].@dbName.dbo.[LL]'
exec sp_executesql @sql, N'@dbName nvarchar(50)', @dbName = N'[TheDatabase1]'
This gives the error Incorrect syntax near '@dbName'.
Is there any other option I might consider?
PS – the database schema is not within my control.
You cannot parameterize the database name – you will need to concatenate it directly.
Here is very good (though lengthy) article about dynamic SQL, by Erland Sommarskog.