选择qry以使用2个数据库

时间:2015-10-27 15:28:51

标签: sql sql-server-2008

我有以下查询:

SELECT 
     --a.DateEntered,
     --a.InventoryId,
     a.SKU, a.QtyOnHand,
     b.Dateentered AS VDateEntered,
     b.GoLive, b.DateOnSite, b.CostPrice,
     --a.CurrentPrice,
     m.name AS Status,
     hrf.category, hrf.department, hrf.BrandedOB, hrf.Division,
     hrf.Fascia,
     (a.QtyOnHand * b.CostPrice) AS Cost_Value,
     NULL AS Item_Quantity, NULL AS Item,
     NULL AS Season, hrf.Company,
     (a.QtyOnHand * b.CurrentPrice) AS Sellilng_Value,
     b.merchandisingseason, b.CostPrice AS Costprice_RP,
     b.CurrentPrice, b.InventoryID,
     -- a.AverageUnitCost,
     -- a.AverageUnitCost AS RP_Stk_AverageUnitCost,
     -- a.CurrentPrice AS RP_Stk_Current_Price,
     -- a.Statusid,
     -- a.Quantity_Sign,
     (a.QtyOnHand * b.CostPrice) AS Cost_Value_RP,
     (a.QtyOnHand * b.AverageUnitCost) AS AWC_Value     
     -- a.StockReconciliationId,
     -- a.AverageUnitCost,
FROM
    [dbo].[FC03QTY] a
JOIN 
    dbo.inventory b ON a.SKU = b.SKU
LEFT JOIN
    (------Hierarchy-------
     SELECT 
         ih.InventoryId, hry.category, hry.department,
         hry.BrandedOB, hry.Division, hry.Fascia, hry.Company
     FROM
         (SELECT
              ihn.HierarchyNodeId, ihn.InventoryId
          FROM bm.InventoryHierarchyNode IHN
          GROUP BY ihn.HierarchyNodeId, ihn.InventoryId) IH
     JOIN 
         (SELECT 
              g.categoryid, g.category, h.department, i.BrandedOB,
              j.Division, K.Fascia, L.company
          FROM 
              Category g (NOLOCK)
          JOIN
              Department H ON g.departmentid = h.departmentID
          JOIN
              BrandedOB I (NOLOCK) ON h.BrandedOBID = i.BrandedOBID
          JOIN
              Division j (NOLOCK) ON i.divisionid = j.divisionid
          JOIN
              Fascia k (NOLOCK) ON j.fasciaid = k.fasciaID
          JOIN
              company l (NOLOCK) ON k.companyid = l.companyid
          GROUP BY
              g.categoryid, g.category, h.department,
              i.BrandedOB, j.Division, K.Fascia, L.company) HRY ON ih.HierarchyNodeId = hry.CategoryId
     GROUP BY
         ih.InventoryId, hry.category, hry.department,
         hry.BrandedOB, hry.Division, hry.Fascia, hry.Company) HRF ON b.inventoryid = hrf.inventoryid
JOIN
    inventorystatus m (NOLOCK) ON b.statusid = m.statusid

它正在使用2个表 -

  • [dbo]。[FC03QTY] a

  • dbo.inventory b

在SKU级别加入。

[dbo].[FC03QTY]位于临时数据库中,dbo.inventory位于报告数据库中。

如果这些表位于2个不同的数据库上,我怎样才能使用这些表?

任何建议都很受欢迎。

1 个答案:

答案 0 :(得分:2)

在sql server中,表的语法是[database name].[schema name].[table name]

所以你需要这样的东西:

SELECT A.*, B.*
FROM 
     Database1.dbo.Table1 as  A, 
     Database2.dbo.Table2 as  B