0

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

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
4

1 回答 1

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命令,它可能会满足您的需求。

于 2012-12-11T07:06:52.817 回答