Create dynamic table from function in PostgreSQL

后端 未结 3 1658
死守一世寂寞
死守一世寂寞 2021-01-06 12:14

I have table data,

select * from tbltaxamount ;
 id |   taxname   | taxinfoid | taxvalue | taxamt | zoneid | invoiceid | transid 
----+-------------+--------         


        
3条回答
  •  生来不讨喜
    2021-01-06 13:15

    After so may tries I have created below function for creation of the table on the fly and that will display records as above.

    CREATE OR REPLACE FUNCTION taxamount() RETURNS void as $$
    DECLARE
            columnNames RECORD;
        invoiceids RECORD;
    BEGIN
        FOR columnNames IN  SELECT * from pg_tables where tablename = 'tmptable'
            LOOP
                DROP TABLE tmptable ;        
            END LOOP;
        CREATE TABLE tmptable (invoiceid integer PRIMARY KEY);
        FOR columnNames IN SELECT distinct(replace(taxname,' ','')) as taxnames from tbltaxamount
            LOOP
                    EXECUTE 'ALTER TABLE tmptable ADD ' || columnNames.taxnames || ' numeric(9,2) DEFAULT 0';
            END LOOP;
        FOR invoiceids IN SELECT distinct(invoiceid) from tbltaxamount
        LOOP
            EXECUTE 'INSERT INTO tmptable (invoiceid) VALUES (' || invoiceids.invoiceid || ')';
        END LOOP;
        FOR invoiceids IN SELECT * from tbltaxamount
        LOOP
            EXECUTE 'UPDATE tmptable SET ' || replace(invoiceids.taxname,' ','') || ' = ' || invoiceids.taxamt  || ' WHERE invoiceid = ' || invoiceids.invoiceid;
        END LOOP ;
    RETURN;
    END;
    $$ LANGUAGE plpgsql;
    

提交回复
热议问题