如何正确编码INSERT子查询?

时间:2013-08-28 16:15:50

标签: sql sql-server

我测试了SQL的每个部分,它运行正常。

我的WHERE条款有些错误但是......在VS 2012中没有详细设置断点但是......

这应该是使用MS SQL SERVER的子查询的INSERT语句的代码吗?

INSERT INTO Emails (email, insertDate) 
VALUES (@Email, @DateToday) 
WHERE NOT EXISTS (SELECT Emails.email 
                  FROM Emails WHERE Emails.email = @Email);

4 个答案:

答案 0 :(得分:5)

INSERT INTO Emails (email, insertDate) 
SELECT @Email, @DateToday
WHERE NOT EXISTS (SELECT Emails.email 
                  FROM Emails WHERE Emails.email = @Email);

答案 1 :(得分:2)

这将有效

INSERT INTO Emails (email, insertDate) 
SELECT @Email, @DateToday
WHERE NOT EXISTS (SELECT Emails.email 
                  FROM Emails WHERE Emails.email = @Email)

更好的解决方案可能是电子邮件列中的唯一索引

答案 2 :(得分:2)

尝试使用以下内容:

"INSERT INTO Emails (email, insertDate) VALUES ('@Email', '@DateToday') WHERE NOT EXISTS (SELECT Emails.email FROM Emails WHERE Emails.email = '@Email');"

答案 3 :(得分:0)

INSERT INTO Emails (email, insertDate) 
SELECT Email, DateToday
WHERE NOT EXISTS (SELECT Emails.email 
                  FROM Emails WHERE Emails.email = Email)

它会将email设置为非空列唯一索引