mysqlstored-proceduresrowcountrows-affected

MySQL ROW_COUNT() not working in Prepare statement


What I'm doing.

I've a procedure where I'm deleting rows.

I'm getting var_SelectedIds as , separated UUID()

then

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;

What I've alread tried.

// 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

The text must represent a single statement, not multiple statements.

I also tried

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

I'm not able to get how may rows got deleted.


Solution

  • You need to execute SELECT ROW_COUNT() right after EXECUTE and before 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;