如何在Excel中使用SQL联接

时间:2013-03-08 22:40:53

标签: sql excel join

我在一年前看到一个更新的问题,这使我在解决方案方面走了很长一段路,但却引发了更多问题而不是答案。

首先我要说的是,我不是SQL(DB2,SQLServer,Oracle)的“新手”,但我是在Excel中使用SQL的相对“新手”。此外,我在2010年工作,但必须保持与2003年的兼容性。

我要做的是将一张纸上的数据与另一张相匹配并报告异常。我想从'Open Lines'中选取6列并将它们与'Back Orders'中的3列匹配,并仅显示例外情况。 'Open Lines'可以是1..n,'Back Orders'可以是0..n。我只想抓住存在“后退订单”的行。

要编写普通的SQL,我会这样做:

SELECT 
O.[Part Number], O.[Part Desc], O.[Source Domain], O.[Ship Qty], O.[Date Created],
B.[Dest Domain], B.[Quantity], B.[Date Created] 
FROM [OPEN LINES] O
JOIN [Back Orders] B ON O.[Part Number] = B.[Part Number]
WHERE B.[Part Number] IS NOT NULL
ORDER BY O.[Part Number] 

问题是我无法在没有错误的情况下通过连接。这是我到目前为止所做的。

rs.Open "SELECT [OPEN LINES$].[Part Number], [OPEN LINES$].[Part Desc], " $ _
"[OPEN LINES$]. [Source Domain], " & _
"[OPEN LINES$].[Ship Qty], [OPEN LINES$].[Date Created] " & _
"FROM [OPEN LINES$] " & _
"JOIN [Back Orders$] ON [OPEN LINES$].[Part Number] = [Back Orders$].[Part Number] " & _
"ORDER BY [OPEN LINES$].[Part Number] ;", cn

感谢您提供的任何帮助。

戈德

1 个答案:

答案 0 :(得分:3)

试试这个:

rs.Open "SELECT [OPEN LINES$].[Part Number], [OPEN LINES$].[Part Desc], " $ _
    " [OPEN LINES$]. [Source Domain], " & _
    " [OPEN LINES$].[Ship Qty], [OPEN LINES$].[Date Created] " & _
    " FROM [OPEN LINES$], [Back Orders$] " & _
    " WHERE [OPEN LINES$].[Part Number] = [Back Orders$].[Part Number] " & _
    " ORDER BY [OPEN LINES$].[Part Number]", cn

您不需要结尾分号。

这是一个更简单的例子(在XL2010中测试)

Sub SqlJoin()

    Dim oConn As New ADODB.Connection
    Dim oRS As New ADODB.Recordset
    Dim sPath
    Dim sSQL As String

    sSQL = "select a.blah from <t1> a, <t2> b where a.blah = b.blah"

    sSQL = Replace(sSQL, "<t1>", Rangename(Sheet1.Range("A1:A5")))
    sSQL = Replace(sSQL, "<t2>", Rangename(Sheet1.Range("C1:C3")))

    If ActiveWorkbook.Path <> "" Then
      sPath = ActiveWorkbook.FullName
    Else
      MsgBox "Workbook being queried must be saved first..."
      Exit Sub
    End If

    oConn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & sPath & "';" & _
                 "Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';"

    oRS.Open sSQL, oConn

    If Not oRS.EOF Then
        Sheet1.Range("E1").CopyFromRecordset oRS
    Else
        MsgBox "No records found"
    End If

    oRS.Close
    oConn.Close

End Sub

Function Rangename(r As Range) As String
    Rangename = "[" & r.Parent.Name & "$" & _
                r.Address(False, False) & "]"
End Function