I have a SQL query where I want to specify the names of the columns dynamically.
Let’s say I have a table called TABLE_A, and it has a column by name ID. I was wondering if I could do something like:
SELECT (SELECT 'ID'
FROM DUAL)
FROM TABLE_A
Obviously this is not possible. Is there a better way to this?
SQL does not support dynamic column or table names — you need to use dynamic SQL to get the functionality you want. Dynamic SQL means constructing a string, concatenating as necessary, before submitting the string (containing the query) to the database for interpretation.
Dynamic SQL is supported by most databases, but the syntax is often very different. Oracle provides:
EXECUTE IMMEDIATEThis link provides examples of both.
Lest we forget Little Bobby Tables, dynamic SQL is an increased risk of SQL injection attacks…