使用返回'雪花中的条款?

发布于 2025-02-13 20:03:44 字数 618 浏览 0 评论 0 原文

有没有简单的方法可以在雪花中执行“返回”条款?

例如,在Postgres中,我可以做类似

Col 1 Col 2
1 XCVS
2 FDA
INSERT INTO EXAMPLE_TABLE(COL_2)
VALUES('ABCD')
RETURNING COL_1

的事情,其中​​Col_1设置为自动增量ID,因此,对于上述查询,我​​希望结果“ 3”,并且表格为这样的

Col 1 Col 2
1 XCVS
2 FDAS
3 ABCD

Is there an easy way to do a 'RETURNING' clause in snowflake?

For example in postgres I can do something like

COL 1 COL 2
1 xcvs
2 fdas
INSERT INTO EXAMPLE_TABLE(COL_2)
VALUES('ABCD')
RETURNING COL_1

Where COL_1 is set to be an auto incrementing ID, so for the above query I would expect the result '3' and the table to be like such

COL 1 COL 2
1 xcvs
2 fdas
3 ABCD

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

箹锭⒈辈孓 2025-02-20 20:03:44

雪花似乎缺乏返回 last_insert_id

一种选择是放弃自动启动初级键并使用显式

create sequence example_table_seq1;

create table example_table (
  id number default example_table_seq1.nextval,
  col varchar(255)
);

然后,如果需要知道ID,您可以将其分配给变量并将其传递。这是how Rails does it.

set next_id = select example_table_seq1.nextval from dual;

insert into example_table (id, col)
values ($next_id, 'ABCD');

或使用CTE。

with next_id as (
  select example_table_seq1.nextval as id from dual
)
insert into example_table (id, col)
select next_id.id, 'ABCD' from next_id;

如果不这样做,请让默认情况发生。

insert into example_table (col)
values ('ABCD');

使用序列的优点,vs 从example_table 中选择Max(ID)+1,IS NextVal 将始终返回新的唯一ID。即使您同时执行了很多插入,也没有使用重复ID的危险,也不需要锁和交易。

Snowflake seems to lack returning or last_insert_id.

One option is to forego auto-incrementing primary keys and use a explicit sequence.

create sequence example_table_seq1;

create table example_table (
  id number default example_table_seq1.nextval,
  col varchar(255)
);

Then, if need to know the ID, you can assign it to a variable and pass it in. This is how Rails does it.

set next_id = select example_table_seq1.nextval from dual;

insert into example_table (id, col)
values ($next_id, 'ABCD');

Or using a CTE.

with next_id as (
  select example_table_seq1.nextval as id from dual
)
insert into example_table (id, col)
select next_id.id, 'ABCD' from next_id;

And if you don't, let the default happen.

insert into example_table (col)
values ('ABCD');

The advantage of using a sequence, vs select max(id)+1 from example_table, is nextval will always return a new unique ID. Even if you're doing a lot of inserts at the same time, there's no danger of using a duplicate ID, and no need for locks nor transactions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文