MySQL SELECT 语句:如何将变量的<b>value</b> 显示到COLUMN 标题中? [重复]

问题描述 投票:0回答:2

如何将变量的值放入 SELECT 语句的 COLUMN 标题中,如下所示:

SET @myCaption := "This is my message:";
SET @myMessage := "Hello everyone!";
SELECT @myMessage     /*   as @myCaption */    ;

我想看到这个结果:

+---------------------+
| This is my message: |
+---------------------+
| Hello everyone!     |
+---------------------+

但遗憾的是,我得到的是:

+-----------------+
| @myMessage      |
+-----------------+
| Hello everyone! |
+-----------------+

使用 SELECT ... AS ... AS ... 不允许使用变量

– 列名可以有注释——是否有办法在列标题中显示这样的注释??

– 这没有帮助: 如何使用 select 语句的结果作为列名?


编辑:

我已经把它放到一些PROCEDURE announcement(title, text), 所以我可以这样调用它: announce("这是我的标题...", "这是正文。");

DROP PROCEDURE IF EXISTS announce;
DELIMITER //
CREATE PROCEDURE announce(title VARCHAR(32), text VARCHAR(255))
  BEGIN
    SET @query1 = CONCAT('SELECT "', text, '" AS "', title, '"');
    PREPARE query2 FROM @query1; 
    EXECUTE query2;
 End;     //
DELIMITER ;

call announce("This is my heading ...", "And this is the text.");

想要的结果:

+------------------------+
| This is my heading ... |
+------------------------+
| And this is the text.  |
+------------------------+

感谢@SelVazi 的准备和执行!

mysql variables select title caption
2个回答
2
投票

您可以使用准备好的语句来完成它,如下所示:

SET @myCaption := "This is my message:";
SET @myMessage := "Hello everyone!";
SET @sql = concat('SELECT "', @myMessage, '" AS "', @myCaption,'"');


PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

0
投票

选择@myMessage

工会

选择@myCaption

© www.soinside.com 2019 - 2024. All rights reserved.