What is the usage of “begin end” in MySQL?
In MySQL, BEGIN and END are mainly used to define a code block that can be used in stored procedures, functions, or triggers. The code block contains a series of SQL statements that can control the execution flow of those statements.
The specific usage is as follows:
- Using BEGIN and END in stored procedures.
DELIMITER //
CREATE PROCEDURE myProcedure()
BEGIN
SELECT * FROM myTable;
END //
DELIMITER ;
- Use BEGIN and END in a function.
DELIMITER //
CREATE FUNCTION myFunction() RETURNS INT
BEGIN
DECLARE result INT;
SET result = (SELECT COUNT(*) FROM myTable);
RETURN result;
END //
DELIMITER ;
- Using BEGIN and END in triggers.
DELIMITER //
CREATE TRIGGER myTrigger BEFORE INSERT ON myTable
FOR EACH ROW
BEGIN
SET NEW.created_at = NOW();
END //
DELIMITER ;
In the given example, BEGIN and END are used to mark the beginning and end of a code block, where a series of SQL statements can be included to achieve complex logic control or data processing operations.