Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stored Procedure with ALTER TABLE

I have a need to sync auto_increment fields between two tables in different databases on the same MySQL server. The hope was to create a stored procedure where the permissions of the admin would let the web user run ALTER TABLE [db1].[table] AUTO_INCREMENT = [num]; without giving it permissions (That just smells of SQL injection).

My problem is I'm receiving errors when creating the store procedure. Is this something that is not allowed by MySQL?

DROP PROCEDURE IF EXISTS sync_auto_increment;
CREATE PROCEDURE set_auto_increment (tableName VARCHAR(64), inc INT)
BEGIN
ALTER TABLE tableName AUTO_INCREMENT = inc;
END;

like image 979
psayre23 Avatar asked Aug 24 '26 20:08

psayre23


1 Answers

To extend on the discussion on the comments on Chibu's answer... yes, you can use prepared statements. But you got to use CONCAT to create the sentence instead of using PREPARE ... FROM ....

Here is a working solution:

DROP PROCEDURE IF EXISTS set_auto_increment;
DELIMITER //
CREATE PROCEDURE set_auto_increment (_table VARCHAR(64), _inc INT)
BEGIN
    DECLARE _stmt VARCHAR(1024);
    SET @SQL := CONCAT('ALTER TABLE ', _table, ' AUTO_INCREMENT =  ', _inc);
    PREPARE _stmt FROM @SQL;
    EXECUTE _stmt;
    DEALLOCATE PREPARE _stmt;
END//
DELIMITER;

I've learned this form the article Prepared Statement Failure by Michael McLaughlin.

like image 63
Theraot Avatar answered Aug 26 '26 10:08

Theraot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!