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.
asked Jul 30, 2013 at 8:28

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;
answered Jul 30, 2013 at 8:39
Sign up to request clarification or add additional context in comments.

2 Comments

Using plpgsql is actually an overhead here. This could be done with a plain SQL function as well.
@a_horse_with_no_name I know. It is just an example.
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

answered Jul 30, 2013 at 8:55

Comments

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;
answered Jul 30, 2013 at 8:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.