使用用户定义的变量指定列别名

时间:2012-01-08 16:31:15

标签: mysql sql

我想使用用户定义的变量重命名查询的列。

例如:

select id as @rt from table_name

1 个答案:

答案 0 :(得分:3)

这是不可能的。您必须动态创建sql字符串。

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"

您也可以使用MySql在存储过程中执行此操作。请参阅SQL Syntax for Prepared Statements

的MySql文档

它看起来像这样(未经测试):

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$$