【问题标题】:SQLite - Generate GUID/UUID on SELECT INTO statementSQLite - 在 SELECT INTO 语句上生成 GUID/UUID
【发布时间】:2021-06-11 22:59:01
【问题描述】:

我正在尝试为我的应用程序编写一些测试数据。 我要填充的表有一个字符串类型的列,其中包含一个 UUID。 我需要编写一个插入语句来填充此列。

我当前的语句几乎可以工作,但它为所有插入生成相同的 ID。生成的列不必是真正的 UUID,但必须在表中是唯一的。

我的陈述的简化版本如下所示:

SELECT 
null as id,
whi.externalId,
(select lower(hex( randomblob(4)) || '-' || hex( randomblob(2))
         || '-' || '4' || substr( hex( randomblob(2)), 2) || '-'
         || substr('AB89', 1 + (abs(random()) % 4) , 1)  ||
         substr(hex(randomblob(2)), 2) || '-' || hex(randomblob(6)))) as GUID
FROM WorkHerdInventories as whi

这会导致以下结果:

【问题讨论】:

    标签: sql sqlite random android-sqlite blob


    【解决方案1】:

    SQLite 可能会尝试优化代码,因此它只执行一次子查询并为所有行返回相同的UUID
    删除用于获取 UUIDSELECT 语句(反正你不需要它):

    SELECT 
      null id,
      externalId,
      lower(
        hex(randomblob(4)) || '-' || hex(randomblob(2)) || '-' || '4' || 
        substr(hex( randomblob(2)), 2) || '-' || 
        substr('AB89', 1 + (abs(random()) % 4) , 1)  ||
        substr(hex(randomblob(2)), 2) || '-' || 
        hex(randomblob(6))
      ) GUID
    FROM WorkHerdInventories
    

    请参阅demo
    结果:

    id   | externalId | GUID                                
    ---- | ---------- | ------------------------------------
    null |         78 | 55ad2d25-12b7-4a29-b538-41384cc25b84
    null |         79 | d9f49c6a-7627-4e75-a494-987434dea7a2
    null |         80 | f87feaa3-2dad-43fd-97e5-77353b289799
    null |         81 | ff9557e9-3ab4-4423-b92d-e6c0b92620f7
    null |         82 | 4558a483-bd25-45c9-8ffa-eae8168fc8fb
    null |         83 | 9491bbcd-311d-4c64-8418-da522f9201a6
    null |         84 | 8ac52122-b9ae-40fb-b4c6-7c83238ae8d5
    

    【讨论】:

    • 谢谢!你为我节省了很多浪费的时间。
    猜你喜欢
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多