这是迄今为止最好的“序列”解决方案,包装到存储过程中:DELIMITER $$ CREATE PROCEDURE seq_next_id() BEGIN START TRANSACTION; UPDATE serial SET id=LAST_INSERT_ID(id + 1); SELECT LAST_INSERT_ID() AS number; COMMIT; END $$ DELIMITER ;
DROP PROCEDURE IF EXISTS CreateSequence;
DELIMITER :)
CREATE PROCEDURE CreateSequence( sSeqName VARCHAR(32), iSeqValue BIGINT )
BEGIN
IF NOT EXISTS ( SELECT * FROM SEQUENCES WHERE (NM_SEQUENCE = sSeqName) ) THEN
INSERT INTO SEQUENCES (NM_SEQUENCE, VR_SEQUENCE)
VALUES (sSeqName , iSeqValue );
END IF;
END :)
DELIMITER ;
-- CALL CreateSequence( 'MySequence', 0 );
DROP FUNCTION IF EXISTS GetSequenceVal;
DELIMITER :)
CREATE FUNCTION GetSequenceVal( sSeqName VARCHAR(32), iIncrement INTEGER )
RETURNS BIGINT -- iIncrement can be negative
BEGIN
DECLARE iSeqValue BIGINT;
SELECT VR_SEQUENCE FROM SEQUENCES
WHERE ( NM_SEQUENCE = sSeqName )
INTO @iSeqValue;
IF ( iIncrement <> 0 ) THEN
SET @iSeqValue = @iSeqValue + iIncrement;
UPDATE SEQUENCES SET VR_SEQUENCE = @iSeqValue
WHERE ( NM_SEQUENCE = sSeqName );
END IF;
RETURN @iSeqValue;
END :)
DELIMITER ;
-- SELECT GetSequenceVal('MySequence', 1); -- Adds 1 to MySequence value and returns it.