AAFTAB
AAFTAB

Reputation: 1

Postgresql dynamic queries

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......

Upvotes: 0

Views: 64

Answers (1)

Adrian Klaver
Adrian Klaver

Reputation: 19742

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

Upvotes: 1

Related Questions