【问题标题】:postgresql - use just created identity value to return newly inserted rowpostgresql - 使用刚刚创建的标识值返回新插入的行
【发布时间】:2016-05-10 23:12:12
【问题描述】:

使用 SQL Server 我可以编写以下语句...

create table Person(
    id int identity(1,1),
    name varchar(50)
)

insert into Person(name) values ('John')
select * from Person where id = scope_identity()

在 Postgres 中我可以这样做:

CREATE TABLE public.Person
(
  id serial primary key,
  name character varying(10) NOT NULL
)

INSERT INTO Person(name) VALUES ('Smith', 'John') RETURNING id;

我将如何编写一个等效语句,就像我在 SQL 示例中所做的那样,不返回 id,而是刚刚插入的整个行?

【问题讨论】:

    标签: sql postgresql sql-insert


    【解决方案1】:

    正如@cur4so 所说,或者

    INSERT INTO Person(name) VALUES ('Smith', 'John') RETURNING *;
    

    【讨论】:

      【解决方案2】:
      INSERT INTO Person (name) VALUES ('Smith John'); 
      select * from Person where id = currval('person_id_seq'); 
      

      【讨论】:

      • lastval() 是另一种选择。这样你就不需要知道序列名称了
      猜你喜欢
      • 1970-01-01
      • 2014-12-19
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 2015-04-21
      • 1970-01-01
      • 2018-05-14
      • 1970-01-01
      相关资源
      最近更新 更多