如何将 OpenQuery 连接到另一个 Select 语句?

How do you join OpenQuery onto another Select statement?

我已经使用 OpenQuery 编写了语句,现在想将它加入到我的另一个查询中,这样当我 运行 查看它时 returns 一个 table来自两个选择的记录。我该怎么做?

这些是我目前的查询:

SELECT  I.Invoice_ID,
        I.Invoice_Num,
        I.SO_ID,
        I.SO_Num, 
        O.AccountNumber, 
        I.ShipZip               AS PostCode,
        I.RequestedDeliveryDate AS DeliveryDate,
        I.AddDate,
        I.AddUser,
        O.OrgName,
        I.[Status]
    FROM dbo.Org O  
    INNER JOIN dbo.Invoice I ON O.Org_ID = I.Org_ID

(SELECT * FROM OPENQUERY ([TEST-SQL-TEST-02], 'SELECT GoodsOutTest, LoadRef FROM TestWMS.dbo.GoodsTest')

您可以将 openquery 的结果存储在 CTE 或临时 table 中。只是期望大 tables 的性能会很糟糕。

例如

WITH GoodsOut AS (
    SELECT * FROM OPENQUERY (
        [AKW-SQL-TEST-02], 'SELECT GoodsOutNumber, LoadRef FROM DeltaWMS.dbo.GoodsOut'
    )
)

SELECT I.Invoice_Num,
I.SO_ID,
I.SO_Num, 
O.AccountNumber, 
I.ShipZip               AS PostCode,
I.RequestedDeliveryDate AS DeliveryDate,
I.AddDate,
I.AddUser,
O.OrgName,
I.[Status]
FROM dbo.Org O  
INNER JOIN dbo.Invoice I ON O.Org_ID = I.Org_ID
INNER JOIN GoodsOut ON --whatever

为什么不直接字面意思JOIN呢?

SELECT I.Invoice_ID,
       I.Invoice_Num,
       I.SO_ID,
       I.SO_Num,
       O.AccountNumber,
       I.ShipZip AS PostCode,
       I.RequestedDeliveryDate AS DeliveryDate,
       I.AddDate,
       I.AddUser,
       O.OrgName,
       I.[Status],
       GT.GoodsOutTest
FROM dbo.Org O
     INNER JOIN dbo.Invoice I ON O.Org_ID = I.Org_ID
     INNER JOIN OPENQUERY ([TEST-SQL-TEST-02], 'SELECT GoodsOutTest, LoadRef FROM TestWMS.dbo.GoodsTest') GT ON GT.LoadRef = I.Ref; --Guess ON clause, correct to be appropriate for your data.