I'm trying to find a query for sql that will just insert values but not do it should the value exist. Now ive seen alot of examples but they all rely on primary keys or table to table moves. I just want to add a new row in the table and assuming that one of the collumns doesnt have the same value add it. I know the following wont work but its as close to I think it would be and might just clear it up if my writting is not enough.
INSERT INTO table (txtLastName,txtEmail,txtZip) Values ('Tester','firstname.lastname@example.org','12345') WHERE txtLastName <> 'Tester' or WHERE txtEmail <> 'email@example.com' or WHERE txtZip <> '12345'
Using MS SQL Server.
preguntado el 09 de marzo de 12 a las 17:03
Debes crear un
Unique Constraint composed by the three fields (
The links directs you to SQL Server docs, but the concept of unique constraint is RDBMS universal.
Just beware that when you create a Unique Constraint, your duplicate insert will not just fail silently: it will throw an error saying the insert tried to violate the unique constraint. And, of course, it should do that! Make sure your code handles that exception.
INSERT INTO table (txtLastName,txtEmail,txtZip) SELECT 'Tester','firstname.lastname@example.org','12345' WHERE NOT EXISTS (SELECT * FROM table WHERE txtLastName = 'Tester' AND txtEmail = 'email@example.com' AND txtZip = '12345' )