我试图跨多个数据库选择数据。我能够加入数据库但是,我不知道如何动态声明从哪个数据库查询数据。
e.g。
SELECT
UID
,ACCT
,Comp
FROM db1.dbo.tbl1
JOIN db2.dbo.tbl1
ON db2.dbo.tbl1.uid=db1.dbo.tbl1.uid
这个问题是它没有考虑db1中定义的哪个comp。 (comp = comp1,comp2,comp3)。取决于comp的值,查询应该提供结果
(我确定以下是错误的)
SELECT
uid
,acct
,comp
FROM
(case when comp='comp1'
then db2.dbo.tbl1
when comp='comp2'
then db3.dbo.tbl1
when comp='comp3'
then db2.dbo.tbl1
)
(Insert join clause)
(Insert where clause)
答案 0 :(得分:0)
考虑联合查询
SELECT UID, ACCT, Comp
FROM db1.dbo.tbl1
JOIN db2.dbo.tbl1
ON db2.dbo.tbl1.uid = db1.dbo.tbl1.uid
WHERE comp IN ('comp1', 'comp3')
UNION
SELECT UID, ACCT, Comp
FROM db1.dbo.tbl1
JOIN db3.dbo.tbl1
ON db3.dbo.tbl1.uid = db1.dbo.tbl1.uid
WHERE comp='comp2'