PostgresQL:使用键值插入而不是两个列表

ste*_*eel 5 postgresql postgresql-9.2

PostgresQL 允许您插入两个列表,一个是字段名称,另一个是值。

INSERT INTO products (product_no, name, price) VALUES (1, 'Cheese', 9.99);
Run Code Online (Sandbox Code Playgroud)

对于长列表,很难确定您所在的列表索引。有没有办法通过指定列名和值(即键值对)来插入?注意:这与hstore.

IE。

INSERT INTO products (product_no => 1, name => 'Cheese', price => 9.99);
Run Code Online (Sandbox Code Playgroud)

Abe*_*sto 3

对于常规的 DML 来说是不可能的。

作为备选:

使用值列表使 DML 更短:

INSERT INTO products (product_no, name, price) VALUES
  (1, 'Cheese', 9.99),
  (2, 'Sausages', 9.99),
  ...;
Run Code Online (Sandbox Code Playgroud)

或者创建可以通过指定参数执行的函数:

create or replace function insert_product(
  in product_no products.product_no%type, 
  in name products.name%type, 
  in price products.price%type) returns products.product_no%type as $$
  insert into products(product_no, name, price) values (product_no, name, price) returning product_no;
$$ language sql;

select insert_product(1, 'Mashrooms', 1.99); -- Parameters by order 
select insert_product(product_no := 2, name := 'Cheese', price := 9.99); -- Parameters by name
select insert_product(product_no := 3, price := 19.99, name := 'Sosages'); -- Order does mot matter
Run Code Online (Sandbox Code Playgroud)