Mysql Stored Procedure
A company needs a stored procedure that will insert a new user with an appropriate type.
A company needs a stored procedure that will insert a new user with an appropriate type.
Consider the following tables:
TABLE userTypes
id INTEGER NOT NULL PRIMARY KEY, type VARCHAR(50) NOT NULL
TABLE users
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, email VARCHAR(50)NOT NULL, userTypeId INTEGER NOT NULL ,FOREIGN KEY(userTypeId) REFERENCES user Types (id)
Finish the insertUser procedure so that it inserts a user, with these requirements:• id is auto incremented.
• email is equal to the email parameter.
• userTypeld is the id of the userTypes row whose type attribute is equal to the type parameter.
DELIMITER $$
CREATE PROCEDURE insertUser(
IN p_email VARCHAR(50),
IN p_type VARCHAR(50)
)
BEGIN
DECLARE v_userTypeId INT;
-- Get userTypeId from userTypes table
SELECT id INTO v_userTypeId FROM userTypes WHERE type = p_type LIMIT 1;
-- Insert into users table
INSERT INTO users (email, userTypeId) VALUES (p_email, v_userTypeId);
END $$
DELIMITER ;
Comments
Post a Comment