0

I have an SQL query

SELECT c,d FROM tableX where a='str' AND b=var1 ;

I would like to substitute the var1 with a variable. I tried to use plpgsql.

CREATE OR REPLACE FUNCTION foo (var1 integer) 
RETURNS TABLE (c integer, d varchar)  AS
$BODY$
DECLARE 
 aa varchar = 'str';
BEGIN    
RETURN QUERY EXECUTE 
'SELECT c,d FROM tableX where a=aa AND b=@1' using var1;
END;
$BODY$
LANGUAGE plpgsql;

The error is

No operator matches the given name and argument type(s). You might need to add explicit type casts.

3 Answers 3

3

First - the correct way to specify parameters is $1, not @1.

Second - you do not need dynamic sql to pass parameters to the query. Just write something like:

CREATE OR REPLACE FUNCTION foo (var1 integer) 
RETURNS TABLE (c integer, d varchar)  AS
$BODY$
DECLARE 
 aa varchar = 'str';
BEGIN    
 RETURN QUERY SELECT c,d FROM tableX where a=aa AND b=var1;
END;
$BODY$
LANGUAGE plpgsql;
2
  • 1
    Using plpgsql is actually an overhead here. This could be done with a plain SQL function as well. Commented Jul 30, 2013 at 8:45
  • @a_horse_with_no_name I know. It is just an example. Commented Jul 30, 2013 at 8:49
2

Just to practice in PostgreSQL, as a_horse_with_no_name said, it's possible to write function in plain SQL, here's my attempt:

CREATE FUNCTION foo1 (var1 integer) RETURNS TABLE(c int, d text) 
    AS $$ SELECT c,d FROM tableX where a='str' AND b=$1 $$
    LANGUAGE SQL;

SQL FIDDLE EXAMPLE

1

Just try:

CREATE OR REPLACE FUNCTION foo (var1 integer) 
  RETURNS TABLE (c integer, d varchar)  AS
$BODY$
DECLARE 
  aa varchar = 'str';
BEGIN    
RETURN QUERY 
  SELECT c,d FROM tableX where a=aa AND b=var1;
END;

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.