简体   繁体   中英

Can you concatenate two strings to create dynamic column names in PostgreSQL?

I have a form where people can type in a start and end date, as well as a column name prefix.

In the backend, I want to do something along the lines of

SELECT *, CAST('{{startDate}}' AS TIMESTAMP) AS ({{prefix}} + '_startDate')

Is this possible? Basically, I want to dynamically create the name of the new column. The table is immediately returned to the user, so I don't want to mutate the underlying table itself. Thanks!

You can execute dynamic query that you have prepared by using EXECUTE keyword, otherwise it is not possible to have dynamic structure of SQL.

Since you are preparing your SQL outside database, you can use something like:

SELECT *, CAST('{{startDate}}' AS TIMESTAMP) AS {{prefix}}_startDate

Assuming that {{prefix}} is replaced with some string by your template before it is sent to database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM