2

Im currently using PostgreSQL 9.3 and Im trying to work on this function which connects to another database (esms) and the result of the said function will be compared and used in another function within another database (seis).

CREATE OR REPLACE FUNCTION lowest_grade_query(varchar) RETURNS numeric AS $$
DECLARE
test numeric(3,2);
BEGIN

 PERFORM dblink_connect_u('esms_ref', 'dbname=esms user=postgres password=postgres');

 SELECT * INTO test FROM dblink('esms_ref', 'SELECT MAX(to_number(CASE WHEN grade IN (''DRP'', ''INC'')
                                          THEN ''5.00'' 
                                          ELSE grade END, ''9D99'')) 
                         FROM registration
                         WHERE studid=$1') AS lowest_grade(grade numeric(3,2));

 PERFORM dblink_disconnect('esms_ref');

 RETURN test;

END;
$$ LANGUAGE plpgsql;

But when I try this

SELECT lowest_grade_query('2014-0035');

I get this error:

ERROR:  there is no parameter $1
CONTEXT:  Error occurred on dblink connection named "esms_ref": could not execute query.
SQL statement "SELECT *           FROM dblink('esms_ref', 'SELECT MAX(to_number(CASE WHEN grade IN (''DRP'', ''INC'')
                                          THEN ''5.00'' 
                                          ELSE grade END, ''9D99'')) 
                         FROM registration
                         WHERE studid=$1') AS lowest_grade(grade numeric(3,2))"

Where did it go wrong?

1 Answer 1

2

You forgot to transform the parameter $1 for the remote query.
Your query is:

 dblink('esms_ref', 'SELECT * FROM registration WHERE studid=$1')

What is the value for parameter $1? Queries executed by dblink have their own namespace, plpgsql variables are not implicitly propagated there. $1 in the plpgsql function body does not refer to the same as $1 in a dblink (or other dynamic) query. You have to merge the parameter into the query string explicitly:

dblink('esms_ref', 
   format('SELECT * FROM registration WHERE studid=%L', $1))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.