【问题标题】:How to add array of table data type to function as IN parameter?如何添加表数据类型的数组以用作 IN 参数?
【发布时间】:2016-09-05 02:09:42
【问题描述】:

我想使用函数在表中添加多行, 但无法通过 F1(thebook book[]) 作为。 如果有任何解决方案,请提供帮助。


CREATE TABLE book
(
  id smallint NOT NULL DEFAULT 0,       
  bname text,       
  btype text,
  bprices numeric(11,2)[],
  CONSTRAINT key PRIMARY KEY (id )
);

CREATE OR REPLACE FUNCTION save_book(thebook book)
  RETURNS text AS
  $BODY$
DECLARE 
  myoutput text :='Nothing has occured';
BEGIN

  update book set 
  bname=thebook.bname,
  btype=thebook.btype,bprices=thebook.bprices  WHERE id=thebook.id;

  IF FOUND THEN
    myoutput:= 'Record with PK[' || thebook.id || '] successfully updated';
    RETURN myoutput;
  END IF;

  BEGIN
    INSERT INTO book values(thebook.id,thebook.bname,thebook.btype, thebook.bprices);
    myoutput:= 'Record successfully added';           
  END;
  RETURN myoutput;

END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

SELECT save_book(row(111,'the art of living','ABC', array[190,220])::book); 

【问题讨论】:

  • 那么你有答案了吗?

标签: arrays postgresql plpgsql


【解决方案1】:

CREATE OR REPLACE FUNCTION save_book(VARIADIC thebook book[])
  RETURNS void AS
$func$
BEGIN

INSERT INTO book(id, bname, btype, bprices)  -- spell out target columns!
SELECT *
FROM   unnest(thebook) t
ON     CONFLICT (id) DO UPDATE
SET    bname = excluded.bname                -- excluded key word!
     , btype = excluded.btype
     , bprices = excluded.bprices;

END
$func$  LANGUAGE plpgsql;

呼叫:

SELECT save_book('(111,"the art of living",ABCX, "{190,220}")'
               , '(112,"the art of living",ABCY, "{190,220}")'); 

相关:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-06
    • 2012-05-13
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 2012-11-25
    • 2021-12-31
    • 1970-01-01
    相关资源
    最近更新 更多