0

I have table which stores details of each entity(employee, department). I want to build dynamic query from that table.

CREATE TABLE MyTable
(
    Id int primary key,
    EntityId int,
    ColumnName varchar(100),
    tablename varchar(100)
);

INSERT INTO MyTable (Id, EntityId, ColumnName, tableName)
VALUES (1,1,'name','employee');

INSERT INTO MyTable (Id, EntityId, ColumnName, tableName)
VALUES (2,1,'id','employee');

INSERT INTO MyTable (Id, EntityId, ColumnName, tableName)
VALUES (3,1,'salary','employee');

INSERT INTO MyTable (Id, EntityId, ColumnName, tableName)
VALUES (4,2,'name','departement');

INSERT INTO MyTable (Id, EntityId, ColumnName, tableName)
VALUES (5,2,'location','departement');

INSERT INTO MyTable (Id, EntityId, ColumnName, tableName)
VALUES (6,2,'id','departement');

Above is my table and insert scripts, How can I write a query which gives me output something like below.

SELECT id,name,salary from employee

SELECT id,location,name from departement

If i have multiple entity I should multiple select statements.

4
  • 1
    Any particular reason why you want to store it like that? Commented Jan 12, 2017 at 13:31
  • 3
    This is a known anti-pattern called EAV. Do you really want to go down that road? There are better alternatives in Postgres to do that Commented Jan 12, 2017 at 13:32
  • 1
    it sounds like a bad idea Commented Jan 12, 2017 at 13:34
  • @JakubKania I have posted a dummy schema here, but we do have similar schema.. We are storing this for doing bulk update it selects rows from multiple table requested by user.. apologies for not posting original schema for confidentiality. Commented Jan 12, 2017 at 13:34

1 Answer 1

2

If despite the discouraging comments you still want to consider this approach, here is the query that constructs one query per entity:

SELECT entityid,
  'SELECT ' ||
  string_agg(columnname, ', ' ORDER BY id) ||
  ' FROM ' ||
  tablename ||
  ';' AS query
FROM mytable
GROUP BY entityid, tablename;

Result with your example:

 entityid |                   query                   
----------+---------------------------------------------
        1 | SELECT name, id, salary FROM employee;
        2 | SELECT name, location, id FROM departement;
(2 rows)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.