条件更新/插入 - 不正确的语法在' END'

时间:2016-11-02 09:24:49

标签: mysql sql

根据是否存在现有条目,我在编写更新或插入的查询时遇到一些困难。

我正在运行的当前查询是:

IF EXISTS (SELECT 1 FROM dbContactEmails WHERE contID = 1) 
BEGIN 
    UPDATE dbContactEmails 
    SET contEmail = 'test@test.com' 
    WHERE contID = 1 
    AND contCode = 'HOME' 
END 
ELSE 
    INSERT INTO dbContactEmails (contID, contEmail, contCode, contOrder, contActive) 
    VALUES (1, 'test@test.com', 'HOME', 0, 1) 
END

不幸的是,这不起作用,错误"错误的语法接近' END'"被抛出。

1 个答案:

答案 0 :(得分:1)

在ELSE之后放置BEGIN

IF EXISTS (SELECT 1 FROM dbContactEmails WHERE contID = 1) 
BEGIN 
    UPDATE dbContactEmails 
    SET contEmail = 'test@test.com' 
    WHERE contID = 1 
    AND contCode = 'HOME' 
END 
ELSE 
BEGIN
    INSERT INTO dbContactEmails (contID, contEmail, contCode, contOrder, contActive) 
    VALUES (1, 'test@test.com', 'HOME', 0, 1) 
END