om471987
om471987

Reputation: 5627

What is the best way to get rows from different databases?

I have 10 identical databases.

I get the database names at runtime.

I want to store rows into a collection of objects.

I also only want one hit on the database server.

My current approach:-

Can I use Linq + entity framework with one hit to server, without dynamic query and without hampering the performance? Is there any better solution?

Upvotes: 0

Views: 160

Answers (1)

anon
anon

Reputation:

Having no idea what your query is (I asked but you did not supply it), and not sure that you understand it is going to be extremely difficult to supply database names as variables without a "dynamic query", here is a much simpler way to do it IMHO:

DECLARE @sql NVARCHAR(MAX);

SELECT @sql = N'';

SELECT @sql = @sql + CHAR(13) + CHAR(10) + 'UNION ALL'
    --// you will need to fill in your "//appending query" stuff here:
    + ' SELECT ... FROM ' + QUOTENAME(Databases) + '.dbo.tablename'
 FROM #Databases
 WHERE HAS_DBACCESS(Databases) = 1;

SET @sql = STUFF(@sql, 1, 9, '');

EXEC sp_executesql @sql;

Upvotes: 1

Related Questions