Can the names of the queried fields change dynamically?

Note:
This topic has been translated from a Chinese forum by GPT and might contain errors.

Original topic: 查询出来的字段名可以动态变化吗

| username: Jjjjayson_zeng

[TiDB Usage Environment] Production Environment / Testing / Poc
[TiDB Version]
[Reproduction Path] What operations were performed when the issue occurred
[Encountered Issue: Issue Phenomenon and Impact]
[Resource Configuration] Go to TiDB Dashboard - Cluster Info - Hosts and take a screenshot of this page
[Attachments: Screenshots / Logs / Monitoring]

| username: tidb菜鸟一只 | Original post link

Not possible.

| username: zhanggame1 | Original post link

Didn’t you write this alias yourself? What changes do you need?

| username: Miracle | Original post link

The string following “as” is not an expression, so it should not be allowed.

| username: 像风一样的男子 | Original post link

In the application code, you can concatenate SQL yourself and modify it according to variables as you wish.

| username: TiDBer_vfJBUcxl | Original post link

This is a value, checking the current time, which is variable.

| username: 有猫万事足 | Original post link

If you want the column name to be DATE_FORMAT(CURRENT_DATE(),'%W'), it’s simple, just escape it:

select DATE_FORMAT(CURRENT_DATE(),'%W') as 'DATE_FORMAT(CURRENT_DATE(),\'%W\')'

If you want the column name to be something like today’s day, such as Monday, it’s more complicated. You need to execute it at least twice. First, execute:

select DATE_FORMAT(CURRENT_DATE(),'%W')

Get the value of this SQL, which is Monday. Then concatenate this value with:

select DATE_FORMAT(CURRENT_DATE(),'%W') as

This way, you can achieve both the column name and value being Monday.

However, this method is highly discouraged because concatenating SQL poses a risk of SQL injection, which is a security hazard. Generally, to avoid SQL injection, prepared statements are used, like this:

prepare stmt from 'select DATE_FORMAT(CURRENT_DATE(),\'%W\') as ?';

But this is not supported and will result in an error.

If you can’t avoid string concatenation, you can’t completely eliminate the risk of SQL injection. Therefore, although the above method can achieve both the column name and value being Monday, it is highly discouraged.

| username: Fly-bird | Original post link

It doesn’t work.

| username: Kongdom | Original post link

It should not be supported, it can only be done at the application layer. Or use dynamic SQL, but I haven’t practiced dynamic SQL.

| username: andone | Original post link

It won’t work.

| username: kelvin | Original post link

It should not be possible.

| username: swino | Original post link

It’s not possible.

| username: system | Original post link

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.