Mr. Boy
Mr. Boy

Reputation: 63720

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?

Upvotes: 1

Views: 6066

Answers (1)

Ross Smith II
Ross Smith II

Reputation: 12179

You don't need a stored procedure, you can use INSERT ... 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 ;

Upvotes: 2

Related Questions