SQL Server: How to use a database name as a parameter in a stored procedure?

前端 未结 1 937
轻奢々
轻奢々 2021-01-26 18:59

How can I do a join on tables of 2 different db in same domain like

SET DBname = \"sample\"
SELECT *
FROM Table1
INNER JOIN DBname.Tab         


        
相关标签:
1条回答
  • 2021-01-26 19:38

    You have to use dynamic sql:

    @DBname = 'sample';
    declare @sql nvarchar(max);
    
    set @sql = '
    SELECT *
    FROM Table1 INNER JOIN
         @DBname.table2
         On Table1.key = Table2.Key';
    
    set @sql = replace(@sql, '@DBname', @DBname);
    
    exec sp_executesql @sql;
    

    Databases in general -- and SQL Server in particular -- do not allow parameters to represent database names, schema names, table names, or column names.

    0 讨论(0)
提交回复
热议问题