Using Non-SELECT SQL in Stored Programs

When we include a SQL statement that does not return a result set—such as an UPDATE, INSERT, or SET statement—within a stored program, it will execute exactly as it would if it were executed in some other context (such as if it were called from PHP or issued from the MySQL command line).

SQL statements within stored programs follow the same syntax as they would outside of the stored program. The SQL statements have full access to any stored program variables, which can be used wherever a literal or expression would normally be provided to the SQL.

You can use all the major categories of SQL statements inside stored programs. DML, DDL, and utility statements can be used without restriction.

Example 5-1 uses a combination of DDL and DML to create and manipulate the data in a table.

Example 5-1. Embedding non-SELECT statements in stored programs
CREATE PROCEDURE simple_sqls(  )
BEGIN
    DECLARE i INT DEFAULT 1;

    /* Example of a utility statement */
    SET autocommit=0;

    /* Example of DDL statements */
    DROP TABLE IF EXISTS test_table ;
    CREATE TABLE test_table
         (id        INT PRIMARY KEY,
          some_data VARCHAR(30))
      ENGINE=innodb;

    /* Example of an INSERT using a procedure variable */
    WHILE (i<=10) DO
         INSERT INTO TEST_TABLE VALUES(i,CONCAT("record ",i));
         SET i=i+1;
    END WHILE;

    /* Example of an UPDATE using procedure variables*/
    SET i=5;
    UPDATE test_table
       SET some_data=CONCAT("I updated row ",i)
     WHERE id=i;

    /* DELETE with a procedure variable */
    DELETE FROM test_table WHERE ...

Get MySQL Stored Procedure Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.