简体   繁体   中英

Add values dynamically in stored procedure

I am currently learning MySQL and trying to find out how to code dynamically for input values.

DELIMITER //

CREATE PROCEDURE add_user(
IN username VARCHAR (16),
IN pass VARCHAR (255),
IN email VARCHAR(255),
IN fname VARCHAR (32),
IN lname VARCHAR (32),
IN age INT )

BEGIN

INSERT INTO users (username, pass, email, fname, lname, age)

VALUES (@username, @pass, @email, @fname, @lname, @age);

INSERT INTO usershobbies (u_id, h_id)

VALUES (LAST_INSERT_ID(), '1');

END; //

DELIMITER ;

When I call the procedure and insert values, I get an error message:

call add_user('bugsbunny', 'Carrot1000', 'bugs@bunny.com', 'Bugs','Bunny', '80');

#1054 - Unknown column 'age' in 'field list'

I appreciate any feedback. Thank you!

This error is telling you that there is no column age in table users . You would need to check the definition of your table (which you did not provide in your question).

Also, when using in/out parameters in MySQL, you should not prefix them with @ . I like to give them a string prefix (like p_ ) do disambiguate from other litteral strings such as column names :

CREATE PROCEDURE add_user(
    IN p_username VARCHAR (16),
    IN p_pass VARCHAR (255),
    IN p_email VARCHAR(255),
    IN p_fname VARCHAR (32),
    IN p_lname VARCHAR (32),
    IN p_age INT 
)    
BEGIN

    INSERT INTO users (username, pass, email, fname, lname)
        VALUES (p_username, p_pass, p_email, p_fname, p_lname);

    INSERT INTO usershobbies (u_id, h_id) VALUES (LAST_INSERT_ID(), '1');
END;

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