Reputation: 4933
I tested each part of the SQL and it works fine.
Something is Wrong with my WHERE
clause however.. not getting much detail setting breakpoints in VS 2012 however...
How should this be code for an INSERT
statement with a subquery using MS SQL SERVER?
INSERT INTO Emails (email, insertDate)
VALUES (@Email, @DateToday)
WHERE NOT EXISTS (SELECT Emails.email
FROM Emails WHERE Emails.email = @Email);
Upvotes: 1
Views: 94
Reputation: 49
INSERT INTO Emails (email, insertDate)
SELECT Email, DateToday
WHERE NOT EXISTS (SELECT Emails.email
FROM Emails WHERE Emails.email = Email)
It will work set email
as a not null column or unique index.
Upvotes: 0
Reputation: 3988
Try to use like following :
"INSERT INTO Emails (email, insertDate) VALUES ('@Email', '@DateToday') WHERE NOT EXISTS (SELECT Emails.email FROM Emails WHERE Emails.email = '@Email');"
Upvotes: 2
Reputation: 51514
This will work
INSERT INTO Emails (email, insertDate)
SELECT @Email, @DateToday
WHERE NOT EXISTS (SELECT Emails.email
FROM Emails WHERE Emails.email = @Email)
But a better solution may be a unique index on the email column
Upvotes: 2
Reputation: 70678
INSERT INTO Emails (email, insertDate)
SELECT @Email, @DateToday
WHERE NOT EXISTS (SELECT Emails.email
FROM Emails WHERE Emails.email = @Email);
Upvotes: 5