By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,062 Members | 1,374 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,062 IT Pros & Developers. It's quick & easy.

How to get field value when field name is in variable

P: 4
I have one view with 3 fields like the view name is myview and it has following sql statement.

Expand|Select|Wrap|Line Numbers
  1. select fn,ln,city from tablea
I created a function like below:-

Expand|Select|Wrap|Line Numbers
  1. create function myfun(in t myview, in f varchar(50)) returns varchar(100) as
Now i want to pass row and name of field and let it return the value from function on basis of field name i pass to the function like

Expand|Select|Wrap|Line Numbers
  1. select myfun(*, 'fn') from myview
this suppose to return value of fn from myfun because i'm passing fn as a parameter name.

hope it is clear, if yes, how i can achieve this?
May 14 '10 #1
Share this Question
Share on Google+
5 Replies

Expert 100+
P: 700
You can use dynamic SQL. See here for EXECUTE command
May 14 '10 #2

P: 4
No execute command didn't worked for me. this is what i did?

execute 't.' || quote_ident(f) into v;

in this case t and f are two parameters of function (as mentioned in question) and i declare v as a variable to get the value, it is not working

but if i do this

v := t.fn;

i get the not sure how to get the value dynamically.
May 14 '10 #3

Expert 100+
P: 700
where is select in that query
execute 't.' || quote_ident(f) into v;
Shouldn't there be somehting like that

Expand|Select|Wrap|Line Numbers
  1. execute 'select '||f||' from '|| t into v;
Or I do not understand your problem.
May 14 '10 #4

P: 4
Thanks for quick report but it is not a table where I can use select so it didn't worked. Even if I try

Expand|Select|Wrap|Line Numbers
  1. select fn into v from t 
Without execute, it doesn't work. I think you didn't get my question.
May 14 '10 #5

P: 4
here is the link to an example and i'm trying to follow this

Expand|Select|Wrap|Line Numbers
  1. CREATE FUNCTION concat_selected_fields(in_t sometablename) RETURNS text AS $$
  2. BEGIN
  3.     RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
  4. END;
  5. $$ LANGUAGE plpgsql;'
in my case , field name is dynamic
May 14 '10 #6

Post your reply

Sign in to post your reply or Sign up for a free account.