如何将变量的值放入 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 的准备和执行!
您可以使用准备好的语句来完成它,如下所示:
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;
选择@myMessage
工会
选择@myCaption