[英]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
我想编写一个 MySQL proc,它接受
userId
和userName
并根据是否存在users.userId = userId
的行对表users
进行插入或更新
I saw a similar question here: MySql create or update row with ip?我在这里看到了一个类似的问题: 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 ...
.您不需要存储过程,您可以使用
INSERT ... ON DUPLICATE KEY UPDATE ...
。 Assuming that userid is the PRIMARY
or a UNIQUE
key, this will work:假设 userid 是
PRIMARY
或UNIQUE
键,这将起作用:
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 ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.