using vars in ddl in procedure call

Started by Gauthier, Daveover 13 years ago4 messagesgeneral
Jump to latest
#1Gauthier, Dave
dave.gauthier@intel.com

Hi:

v9.0.1 on linux.

Trying (failing) a test to see if I can run ddl in a procedure where elements of the ddl are vars. Consider...

create or replace function newcol (text) returns integer as $$
declare
newcol alias for $1;
begin

alter table target add column newcol text;

return(0);

end;
$$ language plpgsql;

This successfully adds a column called "newcol" instead of what I passed it as an arg.

Any suggestions on how to make this work?

Thanks !

#2salah jubeh
s_jubeh@yahoo.com
In reply to: Gauthier, Dave (#1)
Re: using vars in ddl in procedure call

Hello,
you need to use execute command 

i.e.

execute 'alter table ........ ' || newcol || ';'

Regards

________________________________
From: "Gauthier, Dave" <dave.gauthier@intel.com>
To: "pgsql-general@postgresql.org" <pgsql-general@postgresql.org>
Sent: Wednesday, August 29, 2012 4:56 PM
Subject: [GENERAL] using vars in ddl in procedure call

Hi:
 
v9.0.1 on linux.
 
Trying (failing) a test to see if I can run ddl in a procedure where elements of the ddl are vars.  Consider...
 
create or replace function newcol (text) returns integer as $$
declare
  newcol alias for $1;
begin
 
  alter table target add column newcol text;
 
return(0);
 
end;
$$ language plpgsql;
 
This successfully adds a column called "newcol" instead of what I passed it as an arg.
 
Any suggestions on how to make this work?
 
Thanks !

#3Tom Lane
tgl@sss.pgh.pa.us
In reply to: Gauthier, Dave (#1)
Re: using vars in ddl in procedure call

"Gauthier, Dave" <dave.gauthier@intel.com> writes:

Trying (failing) a test to see if I can run ddl in a procedure where elements of the ddl are vars. Consider...

You'll need to construct the command as a string value and then run it
with EXECUTE. Beware of quoting issues (quote_ident and quote_literal
are your friends).

regards, tom lane

#4Gauthier, Dave
dave.gauthier@intel.com
In reply to: Tom Lane (#3)
Re: using vars in ddl in procedure call

Yup, works like a charm.
Thanks Salah and Tom for the advise !
-dave

-----Original Message-----
From: Tom Lane [mailto:tgl@sss.pgh.pa.us]
Sent: Wednesday, August 29, 2012 11:18 AM
To: Gauthier, Dave
Cc: pgsql-general@postgresql.org
Subject: Re: [GENERAL] using vars in ddl in procedure call

"Gauthier, Dave" <dave.gauthier@intel.com> writes:

Trying (failing) a test to see if I can run ddl in a procedure where elements of the ddl are vars. Consider...

You'll need to construct the command as a string value and then run it with EXECUTE. Beware of quoting issues (quote_ident and quote_literal are your friends).

regards, tom lane