如何使用在变量上分配的已找到行的数量并在INSERT语句中使用它?

时间:2014-11-13 07:57:02

标签: mysql

我想获取临时表上的结果数,所以我创建了一个查询,如下所示:

SELECT * FROM tmp_sales_negative; -- Selected all columns on my temporary table

SET @limit = (SELECT FOUND_ROWS()); -- Set a variable assignment named 'limit'

上面的查询工作正常,我得到了正确的结果行数,但是当我在此查询中使用变量名时:

INSERT INTO tmp_credit_memo_receivables(credit_memo_id, amount)
SELECT id, amount FROM credit ORDER BY id DESC LIMIT @limit;

它会在@limit部分提示语法错误。我做错了吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

你必须为此使用动态sql。要使用动态sql,必须在存储过程中执行此操作。

创建如下过程:

DELIMITER $$
CREATE PROCEDURE sp_limit()
BEGIN
SELECT SQL_CALC_FOUND_ROWS * FROM tmp_sales_negative;
SET @limit = (SELECT FOUND_ROWS());
SET @sql = 'INSERT INTO tmp_credit_memo_receivables(credit_memo_id, amount)
SELECT id, amount FROM credit ORDER BY id DESC LIMIT ?;';
PREPARE stmt FROM @sql;
EXECUTE stmt USING @limit;
DEALLOCATE PREPARE stmt;
END $$
DELIMITER ;

然后用

执行它
CALL sp_limit();