1

I want to rename the columns of a query by using user-defined variables.

For example:

select id as @rt from table_name

1 Answer 1

3

This is not possible. You would have to create the sql string dynamically.

C#:

string columnName = "xy";
string sql = "SELECT id AS " + columnName + " FROM table_name";

VB:

Dim columnName As String = "xy"
Dim sql As String = "SELECT id AS " & columnName & " FROM table_name"

You can also do that in a stored procedure with MySql. See MySql documentation for SQL Syntax for Prepared Statements

It would look something like this (not tested):

CREATE PROCEDURE myProc (columnName VARCHAR(30))
BEGIN
SET @sql = CONCAT("SELECT id AS ", columnName, " FROM table_name");
    PREPARE s1 FROM @sql;
    EXECUTE s1;
    DEALLOCATE PREPARE s1;
END$$
Sign up to request clarification or add additional context in comments.

2 Comments

In an answer of this kind, one should hardly be afraid of saying too much about SQL injection. At least, it can do no harm to mention the possible risk thereof.
SQL injection sould not be a problem here, if the column names are defined by the programmer rather than entered by a user. In the latter case names would have to be tested for validity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.