问题
I'm having some problems writing a stored procedure to get next value of Auto Incremented column. I want to be able to pass a table name and have the value returned to a specified variable.
The procedure is as follows:
CREATE PROCEDURE Find_last_AI(
IN table_name VARCHAR(255),
OUT last_AI INT)
BEGIN
SELECT AUTO_INCREMENT
INTO last_AI
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'MySchema'
AND TABLE_NAME = table_name
LIMIT 1;
END;
The problem is, after I call the function like this:
CALL Find_last_AI('MyTable', @out);
SELECT @out;
I get the same wrong result - a numeric value (5) no matter what the table input is. The thing is, when I execute the code as a query the results yield correct values.
SELECT AUTO_INCREMENT
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'MySchema'
AND TABLE_NAME = 'table_name'
LIMIT 1;
It seems that I'm forgetting something in the procedure itself, but I can't see it ?
回答1:
I tried myself like below and it worked fine.
set @tabname = 'tab';
SELECT AUTO_INCREMENT
INTO @incre
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = @tabname
LIMIT 1;
select @incre;
Also Good to mention that, using the query above you will get the next (future) auto_increment
value (nothing but, present value + 1).
EDIT:
Finally got it; problem is with LIMIT 1
in your query. Try the below code and it's guaranteed to work fine (TESTED). Also, don't use any reserved word as variable name.
DELIMITER $$
CREATE PROCEDURE Find_last_AI(IN tname VARCHAR(255), OUT last_AI INT)
BEGIN
SELECT AUTO_INCREMENT
INTO last_AI
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'test'
AND TABLE_NAME = tname;
END$$
DELIMITER ;
Run the procedure like
CALL Find_last_AI('test3', @last_AI);
SELECT @last_AI;
回答2:
to add the value auto_increment you must do it within the procedure, getting the last id and add 1, is a somewhat valid solution I leave SP:
#SP
DELIMITER $$
CREATE OR REPLACE PROCEDURE set_Estados(in Estado VARCHAR(45))
BEGIN
DECLARE validar INT;
DECLARE ID INT;
SELECT COUNT(*) INTO validar FROM table_name WHERE table_row=Estado;
if validar = 0 THEN
SELECT (max(estados_id)+1) INTO ID FROM table_name limit 1;
#the value estados_id its a auto_increment value, just call to add the value...
INSERT INTO table_name(estados_id,estados_estado) VALUES(ID,Estado);
CALL get_Estados(); #SP that show all data...
ELSE
SELECT CONCAT('El Estado: ',Estado,' ya existe.') ESTADO;
END IF;
END$$
DELIMITER ;
CALL set_Estados('Activo');
来源:https://stackoverflow.com/questions/23716915/mysql-procedure-to-get-next-auto-increment