我试图找出插入使用mysql中的条件语句,如INSERT INTO in a CASE statement
SET @foo = 1
SELECT (CASE WHEN 1 THEN (
INSERT INTO table1 (`id`, `column`) VALUE (1, 'a');
SET @bar = SELECT LAST_INSERT_ID();
UPDATE table2 SET c1 = @foo WHERE c2 = @bar
) END)
我按照How do write IF ELSE statement in a MySQL query
的建议使用case
但是当我试着继续这样做时:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INTO ForgeRock (`id`, `productName`, `description`) VALUE (4, 'a','b') ) END)' at line 2
http://sqlfiddle.com/#!9/dcb16/22063
所以我试图采用if / else方法...
SELECT IF(1,(INSERT INTO ForgeRock (`id`, `productName`, `description`) VALUE (4, 'a','b')),0)
但是这会产生同样的错误
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INTO ForgeRock (`id`, `productName`, `description`) VALUE (4, 'a','b')),0)' at line 1
http://sqlfiddle.com/#!9/dcb16/22081
所以我假设在mysql中无法做到这一点? https://stackoverflow.com/a/13681306/1267259 (但OP没有得到同样的错误?)
当我写这个问题时,我发现Using IF ELSE statement based on Count to execute different Insert statements 是使用程序执行此操作的唯一方法吗?
答案 0 :(得分:1)
请记住IF() function和IF statement之间的区别。
您可以实现的一个选项是使用FUNCTION(13.1.12 CREATE PROCEDURE and CREATE FUNCTION Syntax):
/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER //
CREATE FUNCTION `insert_new_value` (`p_foo` INT UNSIGNED) RETURNS TINYINT(1)
DETERMINISTIC
BEGIN
/*
INSERT INTO table1 (`id`, `column`) VALUE (1, 'a');
SET @bar = SELECT LAST_INSERT_ID();
-- UPDATE table2 SET c1 = @foo WHERE c2 = @bar;
UPDATE table2 SET c1 = `p_foo` WHERE c2 = @bar;
*/
INSERT INTO `ForgeRock`
(`id`, `productName`, `description`)
VALUES
(4, 'a', 'b');
RETURN 1;
END//
DELIMITER ;
SET @foo := 1;
-- You can also use CASE expression.
SELECT IF(1, `insert_new_value`(@foo), 0) INTO @`return_value`;
/* CODE FOR DEMONSTRATION PURPOSES */