我在OS X上使用MySQL 5 - Snow Leopard ......
准备好工作代码,从序列表中获取最高序列号ID,然后递增并将其分配到相应的表中:
原始代码的目的是动态增加特定表的最后一个序列ID,并将其对应表的id设置为该新值。
注意:
1。原始代码片段(正在运行):
获取最后一个序列号
replace into my_sequence_id_s set id =
(select max(CONVERT(sequence_id, signed)) from my_table_t);
增加数量
insert into my_sequence_id_s set id = null;
将数字保存为变量
set @dynamicId = last_insert_id();
打印的
select @dynamicId;
2。重构:
DROP PROCEDURE IF EXISTS generate_dynamic_id#
CREATE PROCEDURE generate_dynamic_id
(IN _sequence_table varchar(40),
IN _actual_table varchar(40),
IN _id_field VARCHAR(40),
OUT dynamic_id varchar(40))
BEGIN
-- Get Last Sequence Number
set @getLastSequenceNumberSQL =
concat('REPLACE INTO ', _sequence_table, 'SET ID =
(select max(CONVERT(',_id_field,', signed))
from ', _actual_table, ');');
prepare lastRecordStmt from @getLastSequenceNumberSQL;
execute lastRecordStmt;
deallocate prepare lastRecordStmt;
-- Increments the number.
set @createNewSequenceNumberSQL =
concat('insert into ', _sequence_table ,' set id = null;');
prepare newSequenceNumberStmt from @createNewSequenceNumberSQL;
execute newSequenceNumberStmt;
deallocate prepare newSequenceNumberStmt;
-- Set the number as a dynamic variable.
set @dynamic_id = last_insert_id();
END;
#
第3。这是调用函数(失败):
- 获取动态增加的ID
call generate_dynamic_id(
'my_sequence_id_s', 'my_table_t', 'table_id', @dynamicId);
错误:
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException:
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
'ID = (select max(CONVERT(id_field, signed)) from my_table_t)' at line 1
由于某些奇怪的原因,存储函数或触发器中不允许进行动态函数调用,因此这就是使用存储过程的原因。
如您所见,我在参数中设置varchars,然后尝试将它们连接为字符串并在预准备语句中运行它们。
非常感谢任何帮助......
答案 0 :(得分:3)
concat('REPLACE INTO',_ sequence_table,'SET ID =
_sequence_table和SET ID之间的空格?