title: How to get a result from dynamic SQL in Postgres?
body: <p>Raw Table for which rule are stored in one table named md_formula , which are used to map in destination table</p>
  
  <p><strong>Drop/Create/Insert for <code>raw_dbs_transactiondetailscash</code></strong>:</p>
  
  <pre><code>DROP TABLE raw_dbs_transactiondetailscash
  
  CREATE TABLE raw_dbs_transactiondetailscash(
      accountnumber VARCHAR(100),
      referencecurrency VARCHAR(100),
      transactiondate datetime)
  
  INSERT INTO raw_dbs_transactiondetailscash(
      accountnumber, referencecurrency, transactiondate)
      SELECT 'XYZ','$','01/01/2016'            
  </code></pre>
  
  <p><strong>Drop/Create/Insert  for <code>md_formula</code></strong>:</p>
  
  <pre><code>DROP TABLE MD_Formula 
  
  CREATE TABLE MD_Formula (
      Format VARCHAR(20),
      tbl_Src VARCHAR(200),
      Col_src VARCHAR(500),
      tbl_Des VARCHAR(200),
      Col_des VARCHAR(100),
      Condition VARCHAR(500) )
  
  INSERT INTO md_formula(format, tbl_src, Col_src, tbl_des,Col_des)    
      SELECT 'Dbs','raw_dbs_transactiondetailscash','accountnumber',
              'normalized_transaction','account_number'
      UNION ALL
      SELECT 'Dbs','raw_dbs_transactiondetailscash','referencecurrency',
              'normalized_transaction','currency'
      UNION ALL
      SELECT 'Dbs','raw_dbs_transactiondetailscash','transactiondate',
              'normalized_transaction','trade_date'
  </code></pre>
  
  <p>Get the data from  raw table stored in md_Formula
  Via <code>TSQL</code> (Only One Column Selected for Example)</p>
  
  <p>This will actually execute</p>
  
  <pre><code>SELECT accountnumber
  FROM raw_dbs_transactiondetailscash
  </code></pre>
  
  <p>and get set of data from <code>raw_dbs_transactiondetailscash</code> table</p>
  
  <pre><code>DECLARE @sql VARCHAR(100)
  
  SELECT TOP 1 @sql= 'SELECT '+Col_src+ ' FROM '+tbl_Src FROM MD_Formula
  
  EXEC (@sql)
  </code></pre>
  
  <p>Via <code>Postgres</code> (Dynamic Query is prepared only, how to get data from  raw table in dynamic sql is still a question)</p>
  
  <p>This need to execute</p>
  
  <pre><code>SELECT accountnumber,referencecurrency,transactiondate
  FROM raw_dbs_transactiondetailscash
  </code></pre>
  
  <p>and get result</p>
  
  <pre><code>SELECT 'SELECT '|| string_Agg(col_src,',') ||' FROM ' ||  tbl_src FROM md_formula
  WHERE format='Dbs'
  GROUP BY tbl_src
  </code></pre>