0
DO
$$
    DECLARE 
    loginid varchar :='asdasdw';
    sql_stmt_part   TEXT;
    begin
     sql_stmt_part:=
      'select * from test.tablename where login_id=' loginid; 
     execute sql_stmt_part;

 end 
$$ language plpgsql;

Getting error column 'aadasdw' does not exists......

2
  • 1
    DO cannot return results. Use a function. Commented Oct 7, 2020 at 21:16
  • postgresql.org/docs/current/… - It is how to use external variable in the execute statement Commented Oct 7, 2020 at 22:16

1 Answer 1

1

As mentioned a DO will not return anything. To make the statement work though:


DO
$$
    DECLARE 
    loginid varchar :='asdasdw';
    sql_stmt_part   TEXT;
    begin
     execute  'select * from test.tablename where login_id='|| quote_literal(loginid); 
     

 end 
$$ language plpgsql;

The login variable needs to concatenated to the rest of the string and properly quoted(the quote_literal). This is just one way of doing it. Others can be found here:

https://www.postgresql.org/docs/current/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Adrian Kiaver it's useful for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.