如何在函数内执行delete语句

时间:2016-11-16 15:13:42

标签: postgresql plpgsql

我希望我的应用程序的客户端间接调用DELETE语句或使用函数。这就是我试过的:

CREATE OR REPLACE FUNCTION layer_250_delete(layer_id integer)
    RETURNS bool AS
$BODY$ 
BEGIN    
    EXECUTE 'DELETE FROM layer_250_ WHERE id = $1' USING layer_id;    
    RETURN TRUE;   
END; 
$BODY$
   LANGUAGE plpgsql VOLATILE
   COST 100;
ALTER FUNCTION layer_250_delete(integer)
OWNER TO postgres;

我也尝试过原始查询:

...
DELETE FROM layer_250_ WHERE id = 1';    
RETURN TRUE;
...

但是,当我这样调用此函数(变体1或2)时:

select layer_250_delete(1);

它不会从layer_250_表中删除一行。我在stackoverflow上扫描了几十个线程,但找不到任何与我的任务类似的东西。

结构

CREATE TABLE public.layer_250_
(
  id integer NOT NULL DEFAULT nextval('layer_250__id_seq'::regclass),
  feature_type character varying(100) NOT NULL,
  feature_hash character varying(500) NOT NULL,
  feature_uid character varying(100) NOT NULL,
  geom geometry,
  radius integer,
  group_id integer,
  object_id integer NOT NULL DEFAULT 0,
  row_id integer NOT NULL DEFAULT 0,
  action_time timestamp without time zone NOT NULL DEFAULT now(),
  action_type character varying(255),
  action_user_id integer,
  action_user_ip character varying(255),
  CONSTRAINT layer_250__pkey PRIMARY KEY (id),
  CONSTRAINT layer_250__feature_uid_key UNIQUE (feature_uid),
  CONSTRAINT enforce_dims_geom_layer_250_ CHECK (st_ndims(geom) = 2),
  CONSTRAINT enforce_srid_geom_layer_250_ CHECK (st_srid(geom) = 3857)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE public.layer_250_
  OWNER TO postgres;

1 个答案:

答案 0 :(得分:1)

是的,确实如此:

  t=# create table layer_250_ (id int);
    CREATE TABLE
    t=# insert into layer_250_ select 1;
    INSERT 0 1
    t=# CREATE OR REPLACE FUNCTION layer_250_delete(layer_id integer)
    t-#     RETURNS bool AS
    t-# $BODY$
    t$# BEGIN
    t$#     EXECUTE 'DELETE FROM layer_250_ WHERE id = $1' USING layer_id;
    t$#     RETURN TRUE;
    t$# END;
    t$# $BODY$
    t-#    LANGUAGE plpgsql VOLATILE
    t-#    COST 100;
    CREATE FUNCTION
    t=# ALTER FUNCTION layer_250_delete(integer)
    t-# OWNER TO postgres;
    ALTER FUNCTION
    t=# begin;
    BEGIN
    t=# select layer_250_delete(1);
     layer_250_delete
    ------------------
     t
    (1 row)

    t=# select * from layer_250_;
     id
    ----
    (0 rows)

    t=# end;
    COMMIT