views:

130

answers:

2

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;

A: 

The problem seems to be that you need to change the delimiter. It thinks that the Alter table line is the end of the function. Try this:

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

DELIMITER ;

Sometimes mysql is still picky about letting you use stored procedures, so you can do try this if you still can't run it:

DROP PROCEDURE IF EXISTS sync_auto_increment;
DELIMITER //
CREATE PROCEDURE set_auto_increment (tableName VARCHAR(64), inc INT)
DETERMINISTIC
READS SQL DATA
BEGIN
ALTER TABLE tableName AUTO_INCREMENT = inc;
END//

DELIMITER ;
Chibu
Oh, And I don't think that you can actually use a variable for a table name, so you may have to make different procedures for each table you want to alter...
Chibu
I had actually removed the delimiter for brevity.I tried both your examples and am still getting the following error.<code>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'inc; END' at line 5</code>
psayre23
Wait, you can't use variables for table name, at all?!?I had heard that it might be possible using prepared statements. Does that ring a bell?
psayre23
Well, the MsSQL Manual gives the example: `PREPARE stmt_name FROM "SELECT name FROM Country WHERE code = ?";`. This is the first I've heard of them though. I tried `PREPARE tmp_stmt FROM "SELECT * FROM ? LIMIT 10";` And It gave me the same error. SO, it looks like prepared statements (in my brief attempt, anyway) won't work either. I was setting up procedures to do something to 3 tables with the same structure, and I ended up having to write in:`IF (tablename = 'table_name_1') THEN SELECT * FROM table_name_1`And another `If` for two other tables. I suppose it works... but it's not great.
Chibu
A: 

I think you'll find you can't put Data Definition Language statements into a stored procedure. A possible exception would be CREATE TEMPORARY TABLE. I have searched the MySQL manual for more information on that point; it says the stored procedure may contain a statement_list, but nowhere defines what that means. But I think that's the case.

Brian Hooper