简体   繁体   中英

MySQL procedure to create or update a row in a table

I want to write a MySQL proc which takes userId and userName and does an insert or update into table users dependent on if a row exists where users.userId = userId

I saw a similar question here: MySql create or update row with ip?

But I want to do this in a stored procedure and wondered if that gives any additional tools?

You don't need a stored procedure, you can useINSERT ... ON DUPLICATE KEY UPDATE ... . Assuming that userid is the PRIMARY or a UNIQUE key, this will work:

INSERT INTO user
SET 
userid = ?,
userName = ?
ON DUPLICATE KEY UPDATE
userName = VALUES(userName)

Of course, you could wrap this query in a stored procedure if you want:

DROP PROCEDURE IF EXISTS set_user;

DELIMITER //

CREATE PROCEDURE set_user(
    IN i_userid INT UNSIGNED,
    IN v_userName VARCHAR(50)
)
DETERMINISTIC
MODIFIES SQL DATA
SQL SECURITY INVOKER
BEGIN
    INSERT INTO user
    SET 
    userid = i_userid,
    userName = v_userName
    ON DUPLICATE KEY UPDATE
    userName = VALUES(userName);
END;
//

DELIMITER ;

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