0

Anyone who can help me how to insert bytea from another table in postgres trigger?

CREATE OR REPLACE FUNCTION public.image_insert_trigger()
    RETURNS trigger AS
$BODY$DECLARE
    dyn_sql text;
    tbname text;
    img text;
BEGIN
img:=NEW.img;
tbname:='t'||left(NEW.code,4);
dyn_sql:='INSERT INTO '||tbname||' (id,code,img) VALUES ('||NEW.id||','||NEW.code||','||''''||img::bytea||''''||')';    
execute dyn_sql;
return NULL;
END;$BODY$ 
LANGUAGE plpgsql VOLATILE COST 100;
ALTER FUNCTION public.image_insert_trigger() OWNER TO postgres; 

2 Answers 2

2

Don't use string literals, use parameters

begin
  tbname :='t'||left(NEW.code,4);
  dyn_sql := 'INSERT INTO '||quote_ident(tbname)||' (id,code,img) VALUES ($1, $2, $3)';
  execute dyn_sql 
     using new.id, new.code, new.img;
  return NULL;
END;

I prefer the format() function to define dynamic SQL as it makes the actual SQL easier to read (at least for me)

dyn_sql := format('INSERT INTO %I (id,code,img) VALUES ($1, $2, $3)', tbname);
Sign up to request clarification or add additional context in comments.

Comments

1

It should be much easier to pass the parameters not inline:

dyn_sql:='INSERT INTO '||tbname||' (id,code,img) VALUES ($1,$2,$3)';    
execute dyn_sql using NEW.id, NEW.code, img::bytea;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.