更新并在存储过程中插入操作

时间:2012-12-11 05:40:06

标签: mysql stored-procedures

你能告诉我有什么不对吗?我想要一个可以同时执行更新和插入操作的存储过程。

CREATE PROCEDURE `save_user`(IN `sp_aliasName` VARCHAR(100),IN `sp_password` VARCHAR(100), IN `sp_sex` VARCHAR(100), IN `sp_age` INT(11), IN `sp_userGroup` VARCHAR(100),OUT `sp_number_of_user` INT)    
BEGIN
DECLARE temp INT;
SELECT COUNT(user_id) INTO sp_number_of_user  FROM user WHERE aliasName = sp_aliasname;
temp := sp_number_of_user;
IF temp > 0
THEN
UPDATE user SET aliasName=sp_aliasName,password=sp_password,sex=sp_sex,age=sp_age,userGroup=sp_userGroup 
WHERE aliasName = sp_aliasname ;
ELSE
INSERT INTO user (aliasName,password,sex,age,userGroup)
values (sp_aliasName,sp_password,sp_sex,sp_age,sp_userGroup);
END IF;
END

1 个答案:

答案 0 :(得分:1)

我认为你的程序应该是这样的 -

CREATE PROCEDURE `save_user`(IN `sp_aliasName` VARCHAR(100),IN `sp_password` VARCHAR(100), IN `sp_sex` VARCHAR(100), IN `sp_age` INT(11), IN `sp_userGroup` VARCHAR(100),OUT `sp_number_of_user` INT)    
BEGIN
  DECLARE temp INT;
  SELECT count(user_id) INTO sp_number_of_user FROM user WHERE aliasName = sp_aliasname;
  SET temp := sp_number_of_user;
  IF temp > 0 THEN
    UPDATE user SET aliasName = sp_aliasName, password = sp_password, sex = sp_sex, age = sp_age, userGroup = sp_userGroup
    WHERE aliasName = sp_aliasname;
  ELSE
    INSERT INTO user (aliasName, password, sex, age, userGroup) VALUES (sp_aliasName, sp_password, sp_sex, sp_age, sp_userGroup);
  END IF;
END

我补充说:

  • INT类型为OUT参数
  • UPDATE语句的WHERE子句(检查此条件)

另外,看看INSERT ... ON DUPLICATE KEY UPDATE命令,它可能会做你需要的。