简体   繁体   English

如何在 MySQL 存储过程中模拟打印

[英]How to simulate a print in a MySQL Stored Procedure

I have a MySQL stored procedure with a few cursors.我有一个带有几个游标的 MySQL 存储过程。 I want to print a value to send output back to the client.我想打印一个值以将 output 发送回客户端。 SQLyog Enterprise . SQLyog 企业版

I tried declaring a variable as TEXT and concatenating inside the loop but that does not work, at least not the way I was trying to do it.我尝试将变量声明为 TEXT 并在循环内连接,但这不起作用,至少不是我试图这样做的方式。

DECLARE _output TEXT;
DECLARE _ID INT DEFAULT 0;
DECLARE cur1 CURSOR FOR SELECT ID FROM CodeID;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

OPEN cur1;

REPEAT
  FETCH cur1 INTO _ID;
  IF NOT done THEN
    SET _output = _ID; /*SEE ALT BELOW*/

  END IF;
UNTIL done END REPEAT;
CLOSE cur1;

SELECT _output;

I've tried:我试过了:

SET _output = _output + _ID

and

SET _output = CONCAT(_output,_ID)

but they both just return NULL但他们都只返回 NULL

SET _output = _ID; just gives me the last fetched row.只是给了我最后获取的行。 Which is helpful but not entirely what I wanted.这很有帮助,但不完全是我想要的。

What's the best way to have each fetched row output to screen to reproduce the MySQL print in a MySQL Stored Procedure?让每个提取的行 output 进行筛选以在 MySQL 存储过程中重现 MySQL 打印的最佳方法是什么?

You are doing it correctly with your SELECT _output;您使用 SELECT _output 正确执行此操作; Anything that is selected without an INTO clause will be returned to the client.任何没有 INTO 子句的选择都将返回给客户端。

To get all of them, you could either move the SELECT into the loop (to print each individually), or you could concat them together.要获得所有这些,您可以将 SELECT 移动到循环中(单独打印每个),或者您可以将它们连接在一起。 The problem with your concat returning NULL was because you didn't initialize the _output to anything so it was NULL.你的 concat 返回 NULL 的问题是因为你没有将 _output 初始化为任何东西,所以它是 NULL。 Concatting anything with NULL will return NULL.用 NULL 连接任何东西将返回 NULL。

Try the following:尝试以下操作:

DECLARE _output TEXT DEFAULT '';
DECLARE _ID INT DEFAULT 0;
DECLARE cur1 CURSOR FOR SELECT ID FROM CodeID;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

OPEN cur1;

REPEAT
  FETCH cur1 INTO _ID;
  IF NOT done THEN
    SET _output = CONCAT(",", _ID); /*SEE ALT BELOW*/

  END IF;
UNTIL done END REPEAT;
CLOSE cur1;

SELECT _output;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM