【问题标题】:SQLite UUID as column defaultSQLite UUID 作为列默认值
【发布时间】:2016-09-26 02:48:46
【问题描述】:

我正在尝试为 SQLite 中的 UNIQUEIDENTIFIER 列重现 SQL Server default NEWID() 值。它会生成一个 UUID 作为列的默认值。

如何在 SQLite 中做到这一点?

我找到了这个页面 (Is there UID datatype in SQLITE if Yes then how to generate value for that),他们在其中使用了 select 语句,但它对 DEFAULT 没有好处。

注意:我正在使用为浏览器实现的 SQLite 版本,因为我通过 ionic 和 cordova-sqlite 插件使用它。所以这并不包含 SQLite 提供的所有功能,更重要的是它不包含 RANDOM 函数。

【问题讨论】:

  • 自动增量不够?
  • AUTOINCREMENT 对 UNIQUEIDENTIFIER 类型不执行任何操作。

标签: sqlite


【解决方案1】:

是的,您可以使用create function 添加 UUID 函数。默认情况下,您必须用 C 编写它,但许多 SQLite 驱动程序有办法以它们的母语添加函数。下面是一个使用 DBD::SQLite 的 Perl 示例。

use strict;
use warnings;
use v5.10;

use DBI;
use Data::UUID;

# Connect to the database.
my $dbh = DBI->connect("dbi:SQLite:dbname=test.db", "", "", { RaiseError => 1});

# Create uuid() which calls Perl to generate a uuid.
$dbh->sqlite_create_function("uuid", 0, sub { Data::UUID->new->create_str });

# Create a table using uuid() as the default.
$dbh->do(q[drop table if exists foo]);
$dbh->do(q[
    create table foo (
        id int primary key default (uuid()),
        name text
    )
]);

# Insert some rows using the default id.
$dbh->do(q[
    insert into foo (name) values ("you"), ("me")
]);

# Print out the rows.
my $rows = $dbh->selectall_arrayref(q[select * from foo]);
for my $row (@$rows) {
    say "$row->[0], $row->[1]";
}

结果是。

E9768488-834F-11E6-AA60-F143DC5749B0, you
E976B69C-834F-11E6-AA60-F143DC5749B0, me

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 2012-01-18
    • 2019-07-18
    • 2019-01-06
    • 2020-05-26
    相关资源
    最近更新 更多