简体   繁体   中英

sql if not exists () insert not working

This is my query:

IF NOT EXISTS (SELECT * 
               FROM   teovecerdi 
               WHERE  LocationName = 'Frankfurt' 
               AND    StartDate = '14/02/2015' 
               AND    EndDate = '17/02/2015' 
               AND    Price = '2700') 
INSERT INTO teovecerdi(LocationName, StartDate, EndDate, Price)
VALUES(?,?,?,?)

Can you tell me what's wrong with it? I've also tried with BEGIN and END and it still gives me an error.

EDIT: I handle the parameters correctly.

You can't use an IF statement in a query, it can only be used in a stored procedure.

If you want to do a conditional INSERT , you can use a SELECT query that only returns a row when the condition is met.

INSERT INTO teovecerdi(LocationName, StartDate, EndDate, Price)
SELECT ?, ?, ?, ?
FROM DUAL
WHERE NOT EXISTS (SELECT * 
    FROM   teovecerdi 
    WHERE  LocationName = 'Frankfurt' 
    AND    StartDate = '14/02/2015' 
    AND    EndDate = '17/02/2015' 
    AND    Price = '2700')

您不能在查询或脚本中使用MySQL的过程语法(包括IF这样的语句,以及迭代构造等)。

I am going to suggest a different approach. My guess is that you want LocationName, StartDate, EndDate, Price to be unique. So, let the database do the work for you:

CREATE UNIQUE INDEX unq_teovecerdi_4 on teovecerdi(LocationName, StartDate, EndDate, Price);

Then just be careful to "ignore" errors when you do an insert. My preferred method is:

INSERT INTO teovecerdi (LocationName, StartDate, EndDate, Price)
    VALUES (?, ?, ?, ?)
    ON DUPLICATE KEY UPDATE LocationName = VALUES(LocationName);

The ON DUPLICATE KEY does nothing except absorb the error, when you attempt to insert a duplicate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM