MySQL存储过程语法错误:查找质数

MySQL Stored Procedure Syntax Error: Finding Prime Numbers

提问人:Md. Nahid Hassan 提问时间:9/15/2023 更新时间:9/15/2023 访问量:47

问:

我正在尝试执行一个MySQL存储过程,该过程查找小于或等于1000的质数并使用分隔符打印它们。但是,我遇到了语法错误,我不确定是什么原因导致的。这是我的代码:HackerRank

DELIMITER //

CREATE PROCEDURE findPrimes()
BEGIN
    DECLARE n INT;
    DECLARE divisor INT;
    DECLARE isPrime BOOLEAN;
    
    SET n = 2;
    
    WHILE n <= 1000 DO
        SET divisor = 2;
        SET isPrime = TRUE;
        
        WHILE divisor * divisor <= n DO
            IF n % divisor = 0 THEN
                SET isPrime = FALSE;
                LEAVE;
            END IF;
            SET divisor = divisor + 1;
        END WHILE;
        
        IF isPrime THEN
            SET @result = CONCAT_WS('&', @result, n);
        END IF;
        SET n = n + 1;
    END WHILE;
    SELECT @result;
END;
//
DELIMITER ;

call findPrimes();

我收到以下错误消息:

ERROR 1064 (42000) at line 2: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ';
            END IF;
            SET divisor = divisor + 1;
        END WHILE;
' at line 16

有人可以帮我识别和纠正代码中的语法错误吗?谢谢。

解决语法错误!

SQL MySQL 语法错误

评论


答:

1赞 jmvcollaborator 9/15/2023 #1

您的 LEAVE 需要一个标签,在您的情况下,因为您想打破 While 您需要修改 While 行:

WHILE divisor * divisor <= n DO

自:

mylabel: WHILE divisor * divisor <= n DO

并为 LEAVE 提供标签,以便:

LEAVE mylabel;

完整脚本:

CREATE PROCEDURE findPrimes()
BEGIN
    DECLARE n INT;
    DECLARE divisor INT;
    DECLARE isPrime BOOLEAN;
    
    SET n = 2;
    
    WHILE n <= 1000 DO
        SET divisor = 2;
        SET isPrime = TRUE;
        
        mylabel: WHILE divisor * divisor <= n DO
            IF n % divisor = 0 THEN
                SET isPrime = FALSE;
               LEAVE mylabel;
            END IF;
            SET divisor = divisor + 1;
        END WHILE;
        
        IF isPrime THEN
            SET @result = CONCAT_WS('&', @result, n);
        END IF;
        SET n = n + 1;
    END WHILE;
    SELECT @result;
END;

称之为:

call findPrimes();

奖励曲目:我会使用通用表表达式做一些更简单的事情:

WITH RECURSIVE
    numbers AS (
        SELECT 2 as n
        UNION ALL
        SELECT n + 1 FROM numbers WHERE n < 1000
    ), 
    primes AS (
        SELECT n
        FROM numbers c
        WHERE NOT EXISTS (
            SELECT n FROM numbers c2 WHERE c.n > c2.n AND MOD(c.n, c2.n) = 0
        )
    )
SELECT REPLACE(GROUP_CONCAT(n), ',', '&') FROM primes

评论

0赞 jmvcollaborator 9/15/2023
@Md.NahidHassan,请把我的答案设置为解决方案。谢谢!