Don't do this.
That's the answer. It's a terrible anti-pattern. What purpose does it serve? If the client knows the table it wants data from, then SELECT FROM ThatTable
! If you've designed your database in a way that this is required, you've probably designed it wrong. If your data access layer needs to know if a value exists in a table, it is trivially easy to do the dynamic SQL part in that code. Pushing it into the database is not good.
I have an idea: let's install a device inside elevators where you can type in the number of the floor you want. Then when you press "Go", it moves a mechanical hand over to the correct button for the desired floor and presses it for you. Revolutionary!
Apparently my answer was too short on explanation so I am repairing this defect with more detail.
I had no intention of mockery. My silly elevator example was the very best device I could imagine for succinctly pointing out the flaws of the technique suggested in the question. That technique adds a completely useless layer of indirection, and needlessly moves table name choice from a caller space using a robust and well-understood DSL (SQL) into a hybrid using obscure/bizarre server-side SQL code.
Such responsibility splitting through movement of query construction logic into dynamic SQL makes the code harder to understand. It destroys a perfectly reasonable convention (how a SQL query chooses what to select) in the name of custom code fraught with potential for error.
- Dynamic SQL offers the possibility of SQL injection that is hard to recognize in the front end code or the back end code singly (one must inspect them together to see this).
- At least in SQL Server, dynamic SQL executes with the privileges of the caller, not the running code. I wouldn't be surprised if PostgreSQL functioned the same way. This can render the entire application impervious to a reasonable change in security design, such as using stored procedures where the SP does things the caller had no permission for.
- When a developer must understand what the application code is doing in order to modify it or fix a bug, he'll find it very difficult to get the exact SQL query being executed. SQL profiler can be used, but this takes special privileges and can have negative performance effects on production systems. The executed query can be logged by the SP but this increases complexity for no reason (maintaining new tables, purging old data, etc.) and is totally non-obvious. In fact, some applications are architected such that the developer does not have database credentials, so it becomes almost impossible for him to actually see the query being submitted.
Here's a far better example in pseudo-C# of switching table names based on a parameter:
string sql = string.Format("SELECT * FROM {0};", escapeSqlIdentifier(tableName));
results = connection.Execute(sql);
Every flaw I have mentioned with the other technique is completely absent from this example.