79087417

Date: 2024-10-14 19:11:05
Score: 1
Natty:
Report link

You can select one database dynamically (i.e. test or prod) in a query using OPENQUERY with dynamic SQL sp_executesql. You will need to construct the query dynamically and then run it, as OPENQUERY does not support dynamic queries.

Follow an example:


DECLARE @t NVARCHAR(250) = 'test'; — Database name eg : ( test or prod )

DECLARE @query NVARCHAR(MAX);

DECLARE @storeId int = 1; -- optional filter

SET @query = 'SELECT INTO #Category FROM OPENQUERY([MYSQLLINKEDSERVER], '' SELECT * FROM '+@t+'. category WHERE id = ' + CAST(@storeId AS NVARCHAR(10))===';

EXEC sp_executesql @query;

With this solution, there will be no headache of creating the temporarily table schema whenever you change your database. It also supports filtering with @storeId or any other parameter.

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @storeId
  • Low reputation (1):
Posted by: Mohammed Faruk