【问题标题】:Insert new records only into SQL Table Using VBA使用 VBA 仅将新记录插入 SQL 表
【发布时间】:2017-01-10 15:28:40
【问题描述】:

我有一个包含以下代码的 Excel 工作簿 -

Sub Button1_Click()
    Dim conn As New ADODB.Connection
    Dim iRowNo As Integer
    Dim sFirstName, sLastName As String

    With Sheets("Sheet1")

        'Open a connection to SQL Server
        conn.Open "Provider=SQLOLEDB;" & _
            "Data Source=server1;" & _
            "Initial Catalog=table1;" & _
            "User ID=user1; Password=pass1"

        'Skip the header row
        iRowNo = 2

        'Loop until empty cell in CustomerId
        Do Until .Cells(iRowNo, 1) = ""
            sFirstName = .Cells(iRowNo, 1)
            sLastName = .Cells(iRowNo, 2)

            'Generate and execute sql statement
            ' to import the excel rows to SQL Server table
            conn.Execute "Insert into dbo.Customers (FirstName, LastName) " & _
                         "values ('" & sFirstName & "', '" & sLastName & "')"

            iRowNo = iRowNo + 1
        Loop

        MsgBox "Customers imported."

        conn.Close
        Set conn = Nothing

    End With

End Sub

这会打开与我的数据库的连接并输入来自所述列的值。

主键是数据库上的增量键。问题是它会复制所有值。

我想在 Excel 工作表中添加新的数据行,并且只插入那些不存在的行。

我尝试了不同的方法(“合并”、“如果存在”、“如果不存在”等),但我做不到。

解决方案必须通过 VBA。不能使用 SSMS 设置链接。

我了解可以使用临时表,然后触发执行合并的过程,但我想将其作为最后的手段。还没有读过它(通过我的 MS SQL 圣经书),但我希望没有必要。

---从@Kannan 的回答更新---

VBA 的新部分 -

conn.Execute "IF EXISTS (SELECT 1 FROM dbo.Customers WHERE FirstName = '" &      sFirstName & "' and LastName = '" & sLastName & "') " & _
             "THEN UPDATE dbo.customers SET WHERE Firstname = '" & sFirstName & "' and LastName = '" & sLastName & "' " & _
             "ELSE INSERT INTO dbo.Customers (FirstName, LastName) " & _
             "VALUES ('" & sFirstName & "', '" & sLastName & "')"

这会返回错误“关键字“THEN”附近的语法不正确。

【问题讨论】:

    标签: sql-server excel ssms vba


    【解决方案1】:

    您的 SQL 查询不太正确 - SQL IF 中没有 THEN

    另外,如果它确实存在,你不需要做任何事情,所以如果不存在就使用。

    "IF NOT EXISTS (SELECT 1 FROM dbo.Customers WHERE FirstName = '" & sFirstName & "' and LastName = '" & sLastName & "') " & _
             "INSERT INTO dbo.Customers (FirstName, LastName) " & _
             "VALUES ('" & sFirstName & "', '" & sLastName & "')"
    

    【讨论】:

    • 那就对了。谢谢豆蛙。我之前实际上已经尝试过 IF NOT EXISTS ,但我显然没有做对。我当然没有使用“选择 1”部分。你能告诉我 SELECT 1 是如何工作的吗?
    • 这只是一个常规的选择语句,但不是任何列,而是选择数字 1。所有这些都是为了防止获取所有列详细信息的开销,而您只需要知道 '此行是否存在'而不是'此行中有什么'。
    • 太棒了。再次感谢。一旦最终开始专门从事 SQL 工作,这将使我得到很好的帮助。
    【解决方案2】:

    这应该为你做。

    Sub Button_Click()
    'TRUSTED CONNECTION
        On Error GoTo errH
    
        Dim con As New ADODB.Connection
        Dim rs As New ADODB.Recordset
        Dim strPath As String
        Dim intImportRow As Integer
        Dim strFirstName, strLastName As String
    
        Dim server, username, password, table, database As String
    
    
        With Sheets("Sheet1")
    
                server = .TextBox1.Text
                table = .TextBox4.Text
                database = .TextBox5.Text
    
    
                If con.State <> 1 Then
    
                    con.Open "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Integrated Security=SSPI;"
                    'con.Open
    
                End If
                'this is the TRUSTED connection string
    
                Set rs.ActiveConnection = con
    
                'delete all records first if checkbox checked
                If .CheckBox1 Then
                    con.Execute "delete from tbl_demo"
                End If
    
                'set first row with records to import
                'you could also just loop thru a range if you want.
                intImportRow = 10
    
                Do Until .Cells(intImportRow, 1) = ""
                    strFirstName = .Cells(intImportRow, 1)
                    strLastName = .Cells(intImportRow, 2)
    
                    'insert row into database
                    con.Execute "insert into tbl_demo (firstname, lastname) values ('" & strFirstName & "', '" & strLastName & "')"
    
                    intImportRow = intImportRow + 1
                Loop
    
                MsgBox "Done importing", vbInformation
    
                con.Close
                Set con = Nothing
    
        End With
    
    Exit Sub
    
    errH:
        MsgBox Err.Description
    End Sub
    

    添加对: Microsoft ActiveX 数据对象 2.8 库

    仅供参考,我的床单看起来像这样。

    【讨论】:

      【解决方案3】:

      你可以像这样使用sql查询:

      IF Exists ( Select 1 from dbo.customers where Firstname = '" & sFirstName & "' and LastName = '" & sLastName & "' THEN Update dbo.customers set --other columns where Firstname = '" & sFirstName & "' and LastName = '" & sLastName & "'
      ELSE Insert into dbo.Customers (FirstName, LastName) " & _
                           "values ('" & sFirstName & "', '" & sLastName & "')"
      

      不确定 excel 和 C# 的语法,您可以类似于此查询进行更正

      【讨论】:

      • 嗨@Kannan,我已将此添加到我的代码中并更新了我的问题。你知道为什么我可能会收到我提到的错误。看起来您在第一行中错过了一个右括号。我想我在正确的地方添加了它。
      • 另外,我不太确定如何输入 set 命令。我假设“--other columns”是评论部分?所以我把它拿出来了。
      猜你喜欢
      • 1970-01-01
      • 2011-10-28
      • 2011-05-26
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多