Python PYODBC(MSSQL) script to Insert if record do not exists

28 Views Asked by At

I want to add a script in my MSSQL query to make sure that it will not insert a record if it exists already in the table. I am thinking to put "Where Exists" condition but i am expecting an error since INSERT INTO in pyodbc is a little different on how it is done in mssql studio especially with (?,?,?...).

Thank you for helping

sqlcursor = conn.cursor()
for cnt in cursor:
    get_value1 = cnt["tb_value1"]
    get_value2 = cnt["tb_value2"]
    get_value3 = cnt["tb_value3"]


    sqlcursor.execute("INSERT INTO dbo.sample_table VALUES (?, ?, ?)",
                  (get_value1 , get_value2 , get_value3 ),
                  "WHERE NOT EXISTS.....")
    
conn.commit()
sqlcursor.close()
1

There are 1 best solutions below

0
Mike McPinder On

I think you need to add a SELECT statement before your for loop in which you'll include your WHERE condition, and remove the WHERE in the INSERT statement.