1

I wrote a function in PostgreSQL with a parameter, where I want to insert the parameter value in a database table. The script executes fine but when I call the function I got an error message:

CREATE OR REPLACE FUNCTION sp_load_purchase_order(x int)
  RETURNS void AS
$$ 
declare var_val char;
begin

var_val='p'+i;
insert into purchase_order(
create_uid, 
   create_date, 
   write_date, 
   write_uid, 
   journal_id, 
   date_order, 
   partner_id, 
   amount_untaxed, 
   location_id, 
   company_id, 
   amount_tax, 
   state, 
   pricelist_id, 
   warehouse_id, 
   payment_term_id, 
   amount_total, 
   name, 
   invoice_method, 
   shipped, 
   minimum_planned_date
) 
values(1,now(),now(),1,13,now(),17,1.00,12,1,0.00,'draft',2,1,3,1.00
      ,var_val,'order','f' ,now()
);

end;
$$
  LANGUAGE 'plpgsql';

Error message:

ERROR:  column "i" does not exist
LINE 1: SELECT 'p'+i
                   ^
QUERY:  SELECT 'p'+i
CONTEXT:  PL/pgSQL function sp_load_purchase_order(integer) line 5 at assignment

********** Error **********

ERROR: column "i" does not exist
SQL state: 42703
Context: PL/pgSQL function sp_load_purchase_order(integer) line 5 at assignment

Please help me point out the problem.

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
jay
  • 1,710
  • 2
  • 13
  • 16

3 Answers3

2

And the assignment operator in plpgsql is :=:
The forgotten assignment operator "=" and the commonplace ":="

And do not quote the language name plpgsql!

And you do not need to declare a variable for that. The concatenation can take place in the INSERT statement, which is cheaper.

CREATE OR REPLACE FUNCTION sp_load_purchase_order(x int)
  RETURNS void AS
$func$ 
begin

insert into purchase_order(create_uid, ..., name, ...) 
values(1, ..., 'p' || x, ...);

end
$func$  LANGUAGE plpgsql;
Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
0

Your function parameter is named x but your function body refers to an undeclared variable named i...

Brian A. Henning
  • 1,374
  • 9
  • 24
0

I've done two bad mistakes in my script... one was that undeclared 'i' variable, and another one was my concatenating attempt where i used '+' sign... here is the working code::::

CREATE OR REPLACE FUNCTION sp_load_purchase_order(x int)
  RETURNS void AS
  $$ 
  declare var_val char(10);
begin

var_val='p'||x;
insert into purchase_order(
create_uid, 
   create_date, 
   write_date, 
   write_uid, 
   journal_id, 
   date_order, 
   partner_id, 
   amount_untaxed, 
   location_id, 
   company_id, 
   amount_tax, 
   state, 
   pricelist_id, 
   warehouse_id, 
   payment_term_id, 
   amount_total, 
   name, 
   invoice_method, 
   shipped, 
   minimum_planned_date
) 
values(
1,now(),now(),1,13,now(),17,1.00,12,1,0.00,'draft',2,1,3,1.00,var_val,'order','f' ,now()
);


end;
$$
  LANGUAGE 'plpgsql';
jay
  • 1,710
  • 2
  • 13
  • 16