SQL join from multiple tables

We have a system (based on MS SQL 2008 R2) that has several "input" databases and one "output" database. I would like to write a query that will be read from the output database, and JOINit is to the data in one of the source databases. However, the source table can be one or more separate tables :( The name of the source database is included in the output database, ideally I would like to do something like the following (pseudo-SQL ahoy)

select o.[UID]
      ,o.[description]
      ,i.[data]
from [output].dbo.[description] as o
    left join (select [UID]
                    ,[data]
                from
                    [output.sourcedb].dbo.datatable
                ) as i
        on i.[UID] = o.[UID];

Is there a way to do something like the above - β€œdynamically” specify the database and table to merge each row in the query?

+3
source share
2 answers

, . , , ? , , UID?

:

  • sourcedb .

  • SQL, , , FROM .

    , . , -- . SQL Injection.

  • SQL, exec(), @user353852.

+1

exec, select , , . :

DECLARE @dbName VARCHAR(255), @tableName VARCHAR(255), @colName VARCHAR(255)
...
EXEC('SELECT * FROM ' + @dbName + '.dbo.' + @tableName + ' WHERE ' + @colName + ' = 1') 
+2

Source: https://habr.com/ru/post/1748666/


All Articles