Search code examples
mariadbstring-concatenation

Using concat() to build a column alias name


I am using concat() to create the name for a column name:

set @var = 10;
select col as concat("str1", cast(@var as CHAR), "str2") from table1;

But I get the following syntax error:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ('str1', cast(@var as char), 'str2')

What am I doing wrong?


Solution

  • Try:

    SET @var := 10;
    
    SET @`sql` := CONCAT('select col as ',
                         'str1', cast(@var as CHAR), 'str2',
                         ' from table1');
    
    PREPARE `stmt` FROM @`sql`;
    EXECUTE `stmt`;
    DEALLOCATE PREPARE `stmt`;