在另一个数据库中加入表

时间:2013-05-20 10:29:57

标签: sql-server stored-procedures

我需要在另一个数据库中加入表,但不知道它的名字,我只从procedure参数中获取它。所以我想做这样的事情:

select * from [DB1].dbo.[Table1] t1 
inner join [@DBName].dbo.[Table2] t2 on t1.ID = t2.ID and t1.status = @status;

甚至

select * from [DB1].dbo.[Table1] t1 
inner join [@DBNameAndTableName] t2 on t1.ID = t2.ID and t1.status = @status;

有可能吗?或者我是否必须使用字符串脚本和EXECUTE(@SQL_SCRIPT)

1 个答案:

答案 0 :(得分:3)

试试这个 -

<强>查询:

DECLARE 
      @db_name NVARCHAR(150) = 'DB2'
    , @status INT = 0

DECLARE @SQL NVARCHAR(MAX) = '
SELECT *
FROM [DB1].[dbo].[table1] t1 
JOIN [' + @db_name +'].[dbo].[table1] t2 ON t1.ID = t2.ID 
WHERE t1.status = ' + CAST(@status AS VARCHAR(5))

PRINT @SQL
EXEC sys.sp_executesql @SQL

<强>输出:

SELECT *
FROM [DB1].[dbo].[table1] t1 
JOIN [DB2].[dbo].[table1] t2 ON t1.ID = t2.ID 
WHERE t1.status = 0