Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert new records only into SQL Table Using VBA

I have an Excel workbook with the below code -

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

This opens up a connection to my database and inputs the values from the stated columns.

The primary key is an incremental key on the database. The problem is it will copy ALL values.

I'd like to add new rows of data into the Excel Sheet and only insert those rows that don't already exist.

I've tried different methods ('merge', 'if exist', if not exist', etc.) but I can't get it right.

The solution has to be through VBA. Setting up a link using SSMS is not an option.

I understand that it may be possible to use temporary tables and then trigger a procedure which performs the merge but I want to look into that as a last resort. Haven't read up on it yet (making my way through my MS SQL bible book) but I'm hoping it won't be necessary.

---Update from @Kannan's answer---

New portion of 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 & "')"

This returns error 'Incorrect syntax near the keyword 'THEN'.

like image 202
Jamsandwich Avatar asked Sep 02 '16 13:09

Jamsandwich


People also ask

How do I add a new record to an existing table?

To insert a row into a table, you need to specify three things: First, the table, which you want to insert a new row, in the INSERT INTO clause. Second, a comma-separated list of columns in the table surrounded by parentheses. Third, a comma-separated list of values surrounded by parentheses in the VALUES clause.


1 Answers

Your SQL query isn't quite right - there is no THEN in a SQL IF.

Also, you don't need to do anything if it does exist, so just use if not exists.

"IF NOT EXISTS (SELECT 1 FROM dbo.Customers WHERE FirstName = '" & sFirstName & "' and LastName = '" & sLastName & "') " & _
         "INSERT INTO dbo.Customers (FirstName, LastName) " & _
         "VALUES ('" & sFirstName & "', '" & sLastName & "')"
like image 177
BeanFrog Avatar answered Sep 22 '22 13:09

BeanFrog