How do you create a stored procedure that performs an INSERT operation?
Posted by RoseHrs
Last Updated: July 04, 2024
Creating a stored procedure to perform an INSERT operation in a relational database involves defining the procedure with input parameters and incorporating the SQL INSERT statement within its body. Below is a step-by-step guide to creating such a stored procedure in SQL Server and MySQL as examples.
SQL Server
1. Define the Procedure: Use the CREATE PROCEDURE statement, providing a name for the procedure and specifying any input parameters. 2. Declare the SQL Statement: Use the INSERT INTO statement to define what data should be added to which table. 3. Execute the Procedure: Use EXEC to run the procedure after its creation.
Example
CREATE PROCEDURE InsertEmployee
    @Name NVARCHAR(100),
    @Position NVARCHAR(50),
    @Salary DECIMAL(10, 2)
AS
BEGIN
    INSERT INTO Employees (Name, Position, Salary)
    VALUES (@Name, @Position, @Salary);
END
Execute the Procedure
EXEC InsertEmployee 'John Doe', 'Software Engineer', 60000.00;
MySQL
1. Define the Procedure: Similar to SQL Server, you define the procedure with CREATE PROCEDURE. 2. Use the INSERT Statement: Write the INSERT INTO statement to add records to a table.
Example
DELIMITER //

CREATE PROCEDURE InsertEmployee(
    IN p_Name VARCHAR(100),
    IN p_Position VARCHAR(50),
    IN p_Salary DECIMAL(10, 2)
)
BEGIN
    INSERT INTO Employees (Name, Position, Salary)
    VALUES (p_Name, p_Position, p_Salary);
END //

DELIMITER ;
Execute the Procedure
CALL InsertEmployee('Jane Smith', 'Project Manager', 75000.00);
Key Points
- Input Parameters: Use appropriate data types for the parameters used in the procedure. - Table Names: Ensure that the table to which you are inserting data exists in the database. - Error Handling: Consider including error handling mechanisms within the stored procedure to manage potential issues during insertion. - Permissions: Ensure the user executing the procedure has the necessary permissions to perform insert operations on the corresponding table. This example demonstrates a basic structure but can be expanded with additional functionality like error handling, transaction management, and more complex business logic as required by your application's needs.