How to get field value when field name is in variable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • parry2k
    New Member
    • May 2010
    • 4

    How to get field value when field name is in variable

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

    Code:
    select fn,ln,city from tablea
    I created a function like below:-

    Code:
    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

    Code:
    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?
  • rski
    Recognized Expert Contributor
    • Dec 2006
    • 700

    #2
    You can use dynamic SQL. See here for EXECUTE command

    41.5. Basic Statements # 41.5.1. Assignment 41.5.2. Executing SQL Commands 41.5.3. Executing a Command with a Single-Row Result 41.5.4. Executing Dynamic …

    Comment

    • parry2k
      New Member
      • May 2010
      • 4

      #3
      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 value...so not sure how to get the value dynamically.

      Comment

      • rski
        Recognized Expert Contributor
        • Dec 2006
        • 700

        #4
        where is select in that query
        execute 't.' || quote_ident(f) into v;
        Shouldn't there be somehting like that

        Code:
        execute 'select '||f||' from '|| t into v;
        Or I do not understand your problem.

        Comment

        • parry2k
          New Member
          • May 2010
          • 4

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

          Code:
          select fn into v from t
          Without execute, it doesn't work. I think you didn't get my question.
          Last edited by Niheel; May 19 '10, 07:20 AM. Reason: Please use code tags, proper spelling and grammar

          Comment

          • parry2k
            New Member
            • May 2010
            • 4

            #6
            here is the link to an example and i'm trying to follow this



            Code:
            CREATE FUNCTION concat_selected_fields(in_t sometablename) RETURNS text AS $$
            BEGIN
                RETURN in_t.f1 || in_t.f3 || in_t.f5 || in_t.f7;
            END;
            $$ LANGUAGE plpgsql;'
            in my case , field name is dynamic

            Comment

            Working...