我有2个数据库,即db1,db2。我需要一个从这些dbs(db1,db2)获取数据的查询,每个dbs都有2个表(特许,发票)。
在db1.concessions =>中让步是主要关键。 db1.invoicing => [特许号]是主键
同样在db2.concessions =>中让步是主要关键。 db2.invoicing => [特许号]是主键
在database1
中db1.tbl1 =>特许权表有数据
concession
TH-123
TH-456
FP-789
NZ-609
db1.tbl2 =>发票表有数据
[Concession Number] invoiced_on
TH-322 10.09.10
TH-900 23.10.10
FP-675 04.05.09
NZ-111 19.11.08
幸运的是,在数据库中,特许权的价值是独一无二的。特许权。[特许权] =开具发票。[特许经营号码]不产生数据..
在database2中:
db1.tbl1 =>特许权表有数据
concession
TH-123
FP-789
NZ-999
TH-900
db1.tbl2 =>发票表有数据
[Concession Number] invoiced_on(dd.mm.yy)
TH-456 18.01.06
TH-777 23.10.04
FP-675 03.05.09
NZ-149 26.11.08
在db2让步中是独特的,让步。[特许] =开具发票。[特许号]没有数据..
现在查询应该获取具有公共记录的记录 db1。(concessions.concession OR invoicing.concession number)= db2(concessions.concession OR invoicing.concession number)
在样本数据中应返回TH-123,FP-789,NZ-999,FP-675。
我的第二个问题是有可能将此查询扩展到多个数据库。我无法将数据库的数量更改为1,因为它们已经已修复。请让我知道相同的最佳程序。
我试过这样的事情,有语法错误,
SELECT a.concession as db1_CON_NUMBER FROM db1.dbo.concessions as a UNION
SELECT b.[Concession Number] as db1_CON_NUMBER FROM db1.dbo.invoicing as b
INNER JOIN
SELECT c.concession as db2_CON_NUMBER FROM db2.dbo.concessions as c UNION
SELECT d.[Concession Number] as db2_CON_NUMBER FROM db2.dbo.invoicing as d
ON db1_CON_NUMBER = db2_CON_NUMBER
希望你能回答这两个问题。 感谢您耐心阅读这么长的邮件!
答案 0 :(得分:4)
如果用户具有权限,您可以直接引用其他数据库。
<database>.<user>.<tablename>
是数据库表的完整“路径”。
经常使用
db1.dbo.tbl1 join db2.dbo.tbl2
其中dbo是数据库所有者的默认值,默认情况下,任何不属于特定用户的表都由dbo拥有。
UPDATE
要使查询验证,您可以将其扩展为此
SELECT * FROM
(SELECT a.concession as db1_CON_NUMBER FROM db1.dbo.concessions as a
UNION
SELECT b.[Concession Number] as db1_CON_NUMBER FROM db1.dbo.invoicing as b ) c
INNER JOIN
(SELECT c.concession as db2_CON_NUMBER FROM db2.dbo.concessions as a
UNION
SELECT b.[Concession Number] as db2_CON_NUMBER FROM db2.dbo.invoicing as b ) d
ON db1_CON_NUMBER = db2_CON_NUMBER
但我没有时间检查这是否会返回正确的数据,但您可以进行测试。
答案 1 :(得分:2)
如果数据库位于同一SQL Server实例上,则可以使用3部分命名:
database_name.schema_name.object_name
Using Identifiers As Object Names
如果数据库不在同一个实例上,请创建链接服务器:Linked Servers
Creating Linked Servers (SQL Server Database Engine)
链接服务器允许访问 分布式,异构查询 针对OLE DB数据源。之后 链接服务器已创建,分发 可以针对此运行查询 服务器和查询可以连接表 来自多个数据源。如果 链接服务器定义为 SQL Server的实例,远程存储 程序可以执行。
答案 2 :(得分:0)
select * from(
SELECT a.concession as db1_CON_NUMBER FROM BABMwork6_5_3108.dbo.concessions as a
WHERE (a.manuell_archive_delete! = 'Delete' OR a.manuell_archive_delete IS NULL)
UNION SELECT b.[Concession Number] as db1_CON_NUMBER FROM BABMwork6_5_3108.dbo.invoicing as b) as tbl1
INNER JOIN
(SELECT c.concession as db2_CON_NUMBER FROM BABMwork6_6_2909.dbo.concessions as c
WHERE (c.manuell_archive_delete! = 'Delete' OR c.manuell_archive_delete IS NULL)
UNION SELECT d.[Concession Number] as db2_CON_NUMBER FROM BABMwork6_6_2909.dbo.invoicing as d ) as tbl2
ON tbl1.[db1_CON_NUMBER] = tbl2.[db2_CON_NUMBER]