Search code examples
mysqlmysql-error-1064

Why my Sql Script does not work?


I am newbie to MySQL
I am trying to generate random data and put it into table 'data'

But SQL shell says that my sql code have syntax error
But I can't find why

DECLARE @counter smallint;
DECLARE @A BOOLEAN;
DECLARE @B BOOLEAN;
DECLARE @C int(4);
DECLARE @LABEL BOOLEAN;

SET @counter = 1;
WHILE @counter < 100
    BEGIN
       IF 0.5 > RAND()
            SET @A = TRUE;
        ELSE
            SET @A = FALSE;
        IF 0.5 > RAND()
            SET @B = TRUE;
        ELSE
            SET @B = FALSE;

        SET @C = RAND() * 10
        SET @LABEL = @A ^ @B OR @LABEL > 5

        INSERT INTO data (A,B,C,LABEL) VALUES (@A,@B,@C,@LABEL)
        @count = @count +1
    END

It says that I have syntax problem from declaring variables

can you help me?


Solution

  • Is missing some syntax words:

    • IF... THEN ... ELSE ... END IF;
    • WHILE ... DO ... END WHILE;

    Is important understand that user variables are written as @var_name, so user-defined variables are session-specific. That is, a user variable defined by one client cannot be seen or used by other clients. All variables for a given client session are automatically freed when that client exits. In this case, I think that is not necessary.

    SET, either = or := can be used as the assignment operator.

    Try this:

    delimiter //
    
    CREATE PROCEDURE TEST()
    BEGIN
        DECLARE counter smallint;
        DECLARE A BOOLEAN;
        DECLARE B BOOLEAN;
        DECLARE C int(4);
        DECLARE LABEL BOOLEAN;
    
        SET counter = 1;
        WHILE counter < 100 DO
            IF 0.5 > RAND() THEN
                SET A = TRUE;
            ELSE
                SET A = FALSE;
            END IF;
    
            IF 0.5 > RAND() THEN
                SET B = TRUE;
            ELSE
                SET B = FALSE;
            END IF;
    
            SET C = RAND() * 10;
    
            IF A ^ B OR LABEL > 5 THEN
                SET LABEL = TRUE;
            ELSE
                SET LABEL = FALSE;
            END IF;
    
            INSERT INTO data (A,B,C,LABEL) VALUES (A,B,C,LABEL);
            SET counter = counter +1;
        END WHILE;
    END//