Checking if a record exists already before using SQL INSERT ?

JumboCactuar

Well-known Member
Joined
Nov 16, 2016
Messages
785
Office Version
  1. 365
Platform
  1. Windows
Hi,
not sure if this fits into the excel category but its what im using with ADODB

Code:
Sub insertSQL()

Application.ScreenUpdating = False


    var1 = Sheets("Sheet2").Range("A1")
    
   Set cnn = CreateObject("ADODB.Connection")
    cnn.Open MyConn


    Rw = 2
    
    For i = 2 To Rw
    val1 = Cells(i, 1).Value
    val2 = Cells(i, 2).Value
    val3 = Cells(i, 3).Value
    val4 = Cells(i, 4).Value
    val5 = Cells(i, 5).Value
    val6 = Cells(i, 6).Value
    
    MYSQL = "INSERT INTO umtykbfw_test.`TABLE 1` (Country,IDNO,Yr_2000,Yr_2015,Yr_2025,Yr_2050) VALUES ('" & val1 & "','" & val2 & "','" & val3 & "','" & val4 & "','" & val5 & "','" & val6 & "');"
    cnn.Execute MYSQL
    Next i
    
    cnn.Close
    Set cnn = Nothing




Application.ScreenUpdating = True




End Sub

With the above, if the table already contains the IDNO, i instead want to UPDATE the existing record

I know i can probably do an SQL select on the IDNO then if anything is returned then update, just wondering if theres a better way
 

Excel Facts

Format cells as date
Select range and press Ctrl+Shift+3 to format cells as date. (Shift 3 is the # sign which sort of looks like a small calendar).

Forum statistics

Threads
1,213,510
Messages
6,114,034
Members
448,543
Latest member
MartinLarkin

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top