Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to column name

I'm trying to write a simple postgres function which looks more or less like that:

CREATE OR REPLACE FUNCTION USER_TOTALS(column_name varchar, in_t users) RETURNS float AS $$
  DECLARE
    sum float;
  BEGIN
    sum = (SELECT SUM($1) FROM jobs WHERE jobs.technician_id = in_t.id);
    RETURN sum;
  END;
$$ LANGUAGE plpgsql;

And i need to use it like that:

SELECT users.*, USER_TOTALS('jobs.price', users.*) AS total_price_value FROM users;

Hovewer, that's obviously not working cause SUM() function expects to get a column name but my code passes a varchar to it, so the error says:

Function sum(character varying) does not exist

The question is - can i somehow cast a varchar variable to column name var type? I've been googling for this thing for about 2 hours now and i have no idea how can i make that happen.

like image 771
mbajur Avatar asked Nov 02 '25 01:11

mbajur


2 Answers

A recommended form:

CREATE OR REPLACE FUNCTION USER_TOTALS(column_name varchar, in_t users) 
RETURNS float AS $$
DECLARE 
  sum float;
BEGIN
  EXECUTE format('SELECT SUM(%I) FROM jobs WHERE jobs.technician_id=$1', column_name)
    INTO sum
    USING in_t;
  RETURN sum;
END;
$$ LANGUAGE plpgsql;
like image 198
Pavel Stehule Avatar answered Nov 04 '25 20:11

Pavel Stehule


CREATE OR REPLACE FUNCTION USER_TOTALS(column_name varchar, in_t users) RETURNS float AS $$
DECLARE 
    sum float;
BEGIN
    EXECUTE 'SELECT SUM('||column_name||') FROM jobs WHERE jobs.technician_id='||in_t INTO sum;
    RETURN sum;
END;
$$ LANGUAGE plpgsql;
like image 44
Dwayne Towell Avatar answered Nov 04 '25 19:11

Dwayne Towell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!