我正在尝试创建一个存储过程调用 AddCluster 女巫正在接受参数“title”和“alt”
案例 1:
如果 'title' 在数据库中,则只返回“旧”行!
案例 2:
如果“标题”不在数据库中,则
根据 parmerer 'title' 和 'alt' 插入一行
然后通过LAST_INSERT_ID()选择新添加的行
问题出在情况 2 上,它只返回空!!
-- --------------------------------------------------------------------------------
-- AddCluster Group Routines
-- --------------------------------------------------------------------------------
DELIMITER $$
CREATE DEFINER=`linkbay_dk`@`%` PROCEDURE `AddCluster`(in in_title varchar(45), in in_alt text)
BEGIN
/* check if 'in_title' is in db */
IF EXISTS
(
SELECT count(*) FROM Cluster
WHERE title=in_title
)
THEN
/* returns old Cluster there is in db */
SELECT * FROM Cluster WHERE title=in_title;
ELSE
INSERT INTO Cluster
(
`id`,
`create_at`,
`title`,
`alt`
)
VALUES
(
null,
NOW(),
in_title,
in_alt
);
/* returns the newly added Cluster */
SELECT * FROM Cluster WHERE id=LAST_INSERT_ID();
END IF;
END$$
最佳答案
尝试在不指定 id 的情况下插入:
...
ELSE
INSERT INTO Cluster
(
`create_at`,
`title`,
`alt`
)
VALUES
(
NOW(),
in_title,
in_alt
);
/* returns the newly added Cluster */
...
确保 Cluster.id
是一个 AUTO_INCREMENT
列,只有这样您才能使用 LAST_INSERT_ID()
获取值。
关于MYSQL:存储过程,插入一行,然后通过 LAST_INSERT_ID() 选择它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10676268/