AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 78478508
Accepted
Walter A
Walter A
Asked: 2024-05-14 21:44:22 +0800 CST2024-05-14 21:44:22 +0800 CST 2024-05-14 21:44:22 +0800 CST

Como posso verificar a contagem (*) em um procedimento mysql?

  • 772

Antes de confirmar alterações com um script mysql em um banco de dados, desejo realizar verificações adicionais. Quero reverter uma transação, quando a contagem de registros retornados por uma instrução sql não estiver entre os limites indicados na chamada. O procedimento deve ser chamado como

CALL my_database.checkSQLCount(
    "SELECT count(*) FROM my_table WHERE field1='xxx'",
30,
35);

Fiz um procedimento semelhante para verificar o número de exclusões/atualizações/inserções:

DELIMITER //
 
DROP PROCEDURE IF EXISTS my_database.checkAffectedRows;
CREATE PROCEDURE my_database.checkAffectedRows(IN sqlStatement VARCHAR(1000), IN minAffectedRows INT, IN maxAffectedRows INT)
BEGIN
DECLARE success INT;
DECLARE affectedRows INT;
 
SET @sql := sqlStatement;
-- Print current SQL statement
SELECT @sql AS 'SQL statement:';

-- Execute the provided SQL statement
PREPARE stmt FROM @sql;
EXECUTE stmt;
SELECT ROW_COUNT() INTO affectedRows;

DEALLOCATE PREPARE stmt;
 
-- If the affected rows are outside the specified range, set the success flag to 0
IF affectedRows < minAffectedRows OR affectedRows > maxAffectedRows THEN
  SELECT CONCAT('ERROR: ', affectedRows, ' not between ',  minAffectedRows, ' and ', maxAffectedRows)
    AS 'Check expected nr updates';
  SET success := 0;
ELSE
  SELECT CONCAT('OK: ', affectedRows, ' is between ',  minAffectedRows, ' and ', maxAffectedRows)
    AS 'Check expected nr updates';
  SET success := 1;
END IF;
 
-- Insert the result into the CallResults table
INSERT INTO CallResults (success) VALUES (success);
END //
 
DROP PROCEDURE IF EXISTS my_database.handleCallResults;
CREATE PROCEDURE my_database.handleCallResults()
BEGIN
-- Check if any of the calls failed, if so, rollback the transaction
IF (SELECT COUNT(*) FROM CallResults WHERE success = 0) > 0 THEN
  ROLLBACK;
  SELECT 'Transaction rolled back' AS '=== Data patch end result ===';
ELSE
  -- No Rollback for above calls? Commit!
  COMMIT;
  SELECT 'Transaction committed' AS '=== Data patch end result ===';
END IF;
END //
 
DELIMITER ;
 
-- Start transaction
START TRANSACTION;
 
-- Update table but rollback when amount of updates is not between 1 and 100
CALL my_database.checkAffectedRows(
  "UPDATE myTable SET value='xxx' WHERE idMyTable < 100",
  1,100);

Eu tentei um procedimento como este:

DROP PROCEDURE IF EXISTS myDatabase.checkSQLCount;
CREATE PROCEDURE myDatabase.checkSQLCount(IN countQuery VARCHAR(1000), IN minCount INT, IN maxCount INT)
BEGIN
DECLARE success INT;
DECLARE rowCount INT;
 
SELECT countQuery AS 'SQL statement:';

-- Execute the provided SQL statement without fetching results
SET @stmt = countQuery;
PREPARE stmt FROM @stmt;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
 
-- Retrieve the number of affected rows using FOUND_ROWS() or with ROW_COUNT()
SELECT FOUND_ROWS() INTO rowCount;
 
-- If the matched rows are outside the specified range, set the success flag to 0
IF rowCount < minCount OR rowCount > maxCount THEN
  SELECT CONCAT('ERROR: ', rowCount, ' not between ',  minCount, ' and ', maxCount)
 AS 'Check expected nr matched rows';
  SET success := 0;
ELSE
  SELECT CONCAT('OK: ', rowCount, ' is between ',  minCount, ' and ', maxCount)
    AS 'Check expected nr matched rows';
  SET success := 1;
END IF;

-- Insert the result into the CallResults table
INSERT INTO CallResults (success) VALUES (success);
END //
 

Quando eu chamo isso com

CALL my_database.checkSQLCount(
  "SELECT * FROM my_table WHERE field1='xxx'",
  30,
  35);

a saída mostrará todas as linhas selecionadas, que não quero ver. E quando eu mudo para

CALL my_database.checkSQLCount(
    "SELECT count(*) FROM my_table WHERE field1='xxx'",
30,
35);

o resultado é que encontrei um registro (contendo a contagem)

mysql
  • 1 1 respostas
  • 41 Views

1 respostas

  • Voted
  1. Best Answer
    Mr_Thorynque
    2024-05-14T22:20:01+08:002024-05-14T22:20:01+08:00

    Você pode usar uma variável em sua instrução e depois usá-la:

    SELECT count(*) FROM my_table WHERE field1='xxx' into @rowCount
    

    Editar por Walter A: Isso funcionou após algumas alterações adicionais. Minha solução final parece

    DROP PROCEDURE IF EXISTS myDatabase.checkSQLCount;
    CREATE PROCEDURE myDatabase.checkSQLCount(IN countQuery VARCHAR(1000), IN minCount INT, IN maxCount INT)
    BEGIN
      DECLARE success INT;
      DECLARE rowCount INT;
    
      SELECT countQuery AS '=== SQL statement ===';
    
      SET @stmt = CONCAT(countQuery, ' INTO @rowCount');
    
      PREPARE stmt FROM @stmt;
      EXECUTE stmt ;
      DEALLOCATE PREPARE stmt;
    
      -- If the matched rows are outside the specified range, set the success flag to 0
      IF @rowCount < minCount OR @rowCount > maxCount THEN
        SELECT CONCAT('ERROR: ', @rowCount, ' not between ',  minCount, ' and ', maxCount)
          AS 'Check expected nr matched rows';
        SET success := 0;
      ELSE
        SELECT CONCAT('OK: ', @rowCount, ' is between ',  minCount, ' and ', maxCount)
          AS 'Check expected nr matched rows';
        SET success := 1;
      END IF;
    
      -- Insert the result into the CallResults table
      INSERT INTO myDatabase.CallResults (success) VALUES (success);
    END //
    

    Com este procedimento, assim como o handleCallResultsda pergunta, posso escrever

    -- Start transaction
    START TRANSACTION;
    
    -- Create a temporary table to store the results of each SQL call, always needed
    CREATE TEMPORARY TABLE IF NOT EXISTS bahman.CallResults (success INT);
    
    CALL myDatabase.checkAffectedRows(
      "UPDATE myDatabase.myTable SET currency='xxx' WHERE id < 100",
       1,100);
    
    CALL myDatabase.checkSQLCount(
      "SELECT count(*) FROM myDatabase.myTable WHERE currency='yyy'",
      30, 35);
    
    -- Handle the results and decide whether to commit or rollback the transaction
    CALL myDatabase.handleCallResults();
    
    • 0

relate perguntas

  • mySQL Between Time Range - Onde a hora de início pode ser maior que a hora de término

  • MySQL: Obter contagem de registros consecutivos (data)?

  • Wordpress - Biblioteca de Mídia - Sintaxe SQL

  • docker-compose: Não é possível conectar o serviço de aplicativo ao banco de dados mysql, recebo "Erro: acesso negado para o usuário 'root'@'localhost' (usando a senha: SIM)

  • MySQL Executar um script automático

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle?

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Quando devo usar um std::inplace_vector em vez de um std::vector?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Martin Hope
    Aleksandr Dubinsky Por que a correspondência de padrões com o switch no InetAddress falha com 'não cobre todos os valores de entrada possíveis'? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer Quando devo usar um std::inplace_vector em vez de um std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB Por que o GCC gera código que executa condicionalmente uma implementação SIMD? 2024-02-17 06:17:14 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve