I want to use a registry as a column name but the registry is variable and I don't know when it changes.
Example:
Config (field) = 'Medicine'
FieldContent (another field) = 'Remedy name'
A want to make this:
Medicine (use content of Config as column name) = 'Remedy Name' (as registry)
What have I tried?
SET @CONFIG = SELECT CONFIG;
SELECT FIELDCONTENT AS @CONFIG FROM TABLENAME;
MySql says that I can't use a variable as column name. There's other way?
actual Config Content Medicine RemedyName
Wanted Medicine
RemedyName
Thanks!
How do I give a column a variable name in SQL Server? SELECT Datecolumn as @ColumnName.
User variables are written as @ var_name , where the variable name var_name consists of alphanumeric characters, . , _ , and $ . A user variable name can contain other characters if you quote it as a string or identifier (for example, @'my-var' , @"my-var" , or @`my-var` ). User-defined variables are session specific.
Using Keywords in Tables or Columns Generally, SQL developers advise against using reserved words. However, if you want (or need) to use a reserved word as a table or column name, you can place the respective identifier in special quotation marks, so-called backticks (` `), in the SQL statements.
Display Row Values as Columns in MySQL Dynamically You can customize the above query as per your requirements by adding WHERE clause or JOINS. If you want to transpose only select row values as columns, you can add WHERE clause in your 1st select GROUP_CONCAT statement.
My idea is to use a prepared statement:
SET @config := (SELECT CONFIG FROM yourtable WHERE id=1);
SET @sql := CONCAT('SELECT FIELDCONTENT AS `', @config, '` FROM TABLENAME');
PREPARE stmt FROM @sql;
EXECUTE stmt;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With