MYSQL:increment BINARY变量

b4lqfgs4  于 2023-05-05  发布在  Mysql
关注(0)|答案(1)|浏览(95)

我需要在表中创建一些测试数据。为了透明,我想通过递增UUID主键来手动将它们设置为连续的值。
下面是我的代码:

DROP PROCEDURE IF EXISTS doiterate;
CREATE PROCEDURE doiterate()
BEGIN
    DECLARE v_max int UNSIGNED DEFAULT 10;
    DECLARE v_counter int UNSIGNED DEFAULT 0;
    DECLARE orderId BINARY(16) DEFAULT 0xFE9DCCB10915B0FF11EDCF0000000000;
    DECLARE heldUntil DATETIME DEFAULT '2023-03-31 08:36:35';

    WHILE v_counter <= v_max DO
            SET v_counter = v_counter + 1;
            INSERT INTO experimental_held_orders
            VALUES (orderId, heldUntil);
    
            
    
    SET orderId = orderId + 1;
    SET heldUntil = heldUntil + INTERVAL 1 MINUTE ;
    
    END WHILE;
END;
CALL doiterate();

但我收到一个错误:

[22001][1292] Data truncation: Truncated incorrect DOUBLE value: '\xFE\x9D\xCC\xB1\x09\x15\xB0\xFF\x11\xED\xCF\x00\x00\x00\x00\x00'

请告诉我怎样才能修好它。
PS我不想使用AUTO_INCREMENT
PPS我的表格结构

CREATE TABLE `experimental_held_orders` (
  `OrderId` binary(16) DEFAULT NULL,
  `HeldUntilUtc` datetime DEFAULT NULL
)

UPDATE遵循Andrew的建议,我将初始值和代码更改为:

DROP PROCEDURE IF EXISTS doiterate;
CREATE PROCEDURE doiterate()
BEGIN
    DECLARE v_max int UNSIGNED DEFAULT 10;
    DECLARE v_counter int UNSIGNED DEFAULT 0;
    DECLARE orderId BINARY(16) DEFAULT 0x00000000000000000000000000000000;
    DECLARE heldUntil DATETIME DEFAULT '2023-03-31 08:36:35';
    DECLARE orderId_dec BIGINT;

    WHILE v_counter <= v_max DO
            SET v_counter = v_counter + 1;
            INSERT INTO experimental_held_orders
            VALUES (orderId, heldUntil);

            SET orderId_dec = CONV(orderId, 16, 10);
            SET orderId_dec = orderId_dec + 1;
            SET orderId = CONV(orderId_dec, 10, 16);        
    
            SET heldUntil = heldUntil + INTERVAL 1 MINUTE ;
    
    END WHILE;
END;
CALL doiterate();

但我得到的是:

虽然我期待

0x00000000000000000000000000000000
0x00000000000000000000000000000001
0x00000000000000000000000000000002

等等
0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

ma8fv8wu

ma8fv8wu1#

你可以把十六进制变量转换成十进制,递增它,然后再转换回来。

SET orderId_dec = CONV(orderId, 16, 10);
SET orderId_dec = orderId_dec + 1;
SET orderId = CONV(orderId_dec, 10, 16);

但是你的初始值0xFE9DCCB10915B0FF11EDCF000000000比MySQL BIGINT UNSIGNED大,所以它不会工作。
考虑通过内置的MySQL UUDI()函数生成UUID并将其用作密钥。

SET orderId = UUID();

相关问题