我需要能够加入另一个数据库(在同一台服务器上),并且我需要加入的数据库的名称取决于正在检查的记录。
我有一些东西SELECT *
FROM orders o
INNER JOIN orderdetail od ON od.okey = o.okey
INNER JOIN scheduledetail scheddet on scheddet.odkey = od.odkey
INNER JOIN schedules sched on sched.schedid = scheddet.schedid
INNER JOIN databases db on db.dbdate = sched.releasedate
INNER JOIN [db.dbname].detail det on det.odkey = od.odkey
但是,据我所知,transact SQL不允许这种连接语法。有什么想法吗?
答案 0 :(得分:0)
如果所有详细信息表都具有相同的列,则可以创建一个包装所有详细信息表的视图。
DECLARE @sql varchar(max);
SELECT
@sql = COALESCE(@sql + ' UNION ALL ','CREATE VIEW unified_details AS ')
+ 'SELECT *,'+QUOTENAME([dbname])+' AS [dbname] FROM '+QUOTENAME([dbname])+'.[dbo].[detail]'
FROM databases;
EXEC sp_executesql @sql;
SELECT *
FROM orders o
INNER JOIN orderdetail od ON od.okey = o.okey
INNER JOIN scheduledetail scheddet on scheddet.odkey = od.odkey
INNER JOIN schedules sched on sched.schedid = scheddet.schedid
INNER JOIN databases db on db.dbdate = sched.releasedate
INNER JOIN unified_details det on det.odkey = od.odkey and db.dbname = det.dbname