MySQL ROW_COUNT()在Prepare语句中不起作用

时间:2015-10-19 06:57:33

标签: mysql stored-procedures rowcount rows-affected

我在做什么。

我是一个删除行的程序。

我将var_SelectedIds,分开UUID()

然后

SET     @var_SQLStr = '';   
SET     @var_SQLStr = CONCAT(@var_SQLStr ,'Delete ');
SET     @var_SQLStr = CONCAT(@var_SQLStr ,'FROM DemoTable');        
SET     @var_SQLStr = CONCAT(@var_SQLStr ,'WHERE DemoTableId IN (''',Replace(var_SelectedIds,',',''','''),'''); ');

-- SELECT @var_SQLStr;
PREPARE stmt FROM @var_SQLStr;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

我已经尝试过的尝试。

// This is throwing SQL Syntax ERROR.

SET     @var_SQLStr = '';   
SET     @var_SQLStr = CONCAT(@var_SQLStr ,'Delete ');
SET     @var_SQLStr = CONCAT(@var_SQLStr ,'FROM DemoTable');        
SET     @var_SQLStr = CONCAT(@var_SQLStr ,'WHERE DemoTableId IN (''',Replace(var_SelectedIds,',',''','''),'''); ');
SET     @var_SQLStr = CONCAT(@var_SQLStr ,' SELECT ROWS_COUNT() INTO @var_AffectedRows; ');

-- SELECT @var_SQLStr;
PREPARE stmt FROM @var_SQLStr;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

MySQL Reference

  

文本必须代表单个陈述,而不是多个陈述。

我也试过

START TRANSACTION;

-- Other statements here

SET     @var_SQLStr = '';   
SET     @var_SQLStr = CONCAT(@var_SQLStr ,'Delete ');
SET     @var_SQLStr = CONCAT(@var_SQLStr ,'FROM DemoTable');        
SET     @var_SQLStr = CONCAT(@var_SQLStr ,'WHERE DemoTableId IN (''',Replace(var_SelectedIds,',',''','''),'''); ');

-- SELECT @var_SQLStr;
PREPARE stmt FROM @var_SQLStr;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SELECT ROW_COUNT() INTO @var_AffectedRows
COMMIT;

SELECT @var_AffectedRows AS NoOfRowsDeleted; // 0 output

我无法了解行如何被删除。

1 个答案:

答案 0 :(得分:4)

您需要在SELECT ROW_COUNT()之后和EXECUTE

之前立即执行DEALLOCATE...
START TRANSACTION;

-- Other statements here

SET     @var_SQLStr = '';   
SET     @var_SQLStr = CONCAT(@var_SQLStr ,'Delete ');
SET     @var_SQLStr = CONCAT(@var_SQLStr ,'FROM DemoTable');        
SET     @var_SQLStr = CONCAT(@var_SQLStr ,' WHERE DemoTableId IN (''',Replace(var_SelectedIds,',',''','''),'''); ');
/*you need an additional whitespace here---^ */


-- SELECT @var_SQLStr;
PREPARE stmt FROM @var_SQLStr;
EXECUTE stmt;
SELECT ROW_COUNT() INTO @var_AffectedRows;
DEALLOCATE PREPARE stmt;

SELECT @var_AffectedRows; /*TADAAA!*/

COMMIT;