如何使用VBA将记录从Excel插入DB2数据库

时间:2016-11-02 18:07:29

标签: sql excel vba db2

我想从工作簿中的数据中将记录插入表中, 使用VBA我对插入没有问题,但问题是重复。

只有在数据库中不存在记录时,才能插入Excel中的记录?

这就是我现在拥有的。

此外,我是否可以更新确实存在或需要其他模块的记录?

Sub Button1_Click()

    Dim conn As New ADODB.Connection
    Dim iRowNo As Integer
    Dim sequipid, stype, sname As String

    With Sheets("Sheet1")

        'Open a connection to SQL Server
        conn.Open "Driver={IBM DB2 ODBC DRIVER};Database=XXXX;Hostname=192.168.XXX.XX;Port=50000;Protocol=TCPIP;Uid=" & "XXXX" & ";Pwd=" & "XXXXXX" & ";CurrentSchema=LYNX;"

        'Skip the header row
        iRowNo = 2

        'Loop until empty cell in CustomerId
        Do Until .Cells(iRowNo, 1) = ""
            sequipid = .Cells(iRowNo, 1)
            stype = .Cells(iRowNo, 2)
            sname = .Cells(iRowNo, 3)

            'Generate and execute sql statement to import the excel rows to SQL Server table
            conn.Execute "INSERT INTO OH_TEST_TABLE (EQUIPID, TYPE, NAME) VALUES ('" & sequipid & "','" & stype & "','" & sname & "')"

            iRowNo = iRowNo + 1
        Loop

        MsgBox "RECORD UPDATED"

        conn.Close
        Set conn = Nothing

    End With

End Sub

2 个答案:

答案 0 :(得分:0)

我在DB2 iseries上你可以像这样修改你的查询

post

或者

 conn.Execute "INSERT INTO OH_TEST_TABLE (EQUIPID, TYPE, NAME) select '" & sequipid & "','" & stype & "','" & sname & "' from SYSIBM.SYSDUMMY1 where not exists (select * from OH_TEST_TABLE where EQUIPID='" & sequipid & "')"

答案 1 :(得分:0)

您可以使用这样的合并语句来更新或插入(在大多数现代版本的DB2上):

merge into oh_test_table oh1
using (select * from oh_test_table where equipid='"& sequipid &"') oh2
on oh1.equipid = oh2.equipid
when matched then update set
     type = '"& stype &"',
     name = '"& sname &"'
when not matched then insert
     (equipid, type, name) values ('" & sequipid & "','" & stype & "','" & sname & "')

为了清楚起见,我已将其显示在多行中,而无需额外的VBA格式。