首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >SQLite -在SELECT INTO语句上生成GUID/UUID

SQLite -在SELECT INTO语句上生成GUID/UUID
EN

Stack Overflow用户
提问于 2021-03-14 13:30:10
回答 1查看 2.3K关注 0票数 3

我正在尝试为我的应用程序编写一些测试数据。我要填充的表有一个类型为string的列,该列包含一个UUID。我需要编写一个insert语句来填充此列。

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

我的声明的简化版本如下:

代码语言:javascript
运行
复制
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

这样做的结果如下:

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-14 13:42:52

SQLite可能会尝试优化代码,因此它只执行一次子查询,并对所有行返回相同的UUID

删除用于获取SELECTUUID语句(反正不需要):

代码语言:javascript
运行
复制
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

演示

结果:

代码语言:javascript
运行
复制
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
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66625085

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档