how to create a stored procedure containing request where not exists in mysql database

74 views Asked by At

I have a problem with the request "where not exists" error is :

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 'WHERE NOT EXISTS(SELECT 1 FROM users (WHERE Matricule = @Matricule AND mot_d' at line 11

here is my procedure

create procedure usp_testInsert(
    Matricule int,
    mot_de_passe varchar(10),
    Nom varchar(10) ,
    Prenom varchar(10)
) begin
    INSERT INTO users (
        Matricule,
        mot_de_passe,
        Nom,
        Prenom)
    SELECT
        @Matricule, 
        @mot_de_passe, 
        @Nom, 
        @Prenom 
    WHERE 
        NOT EXISTS (
            SELECT 1 
            FROM users ( 
            WHERE 
                Matricule = @Matricule AND 
                mot_de_passe = @mot_de_passe AND 
                Nom = @Nom AND Prenom = @Prenom
            )
        );
end
1

There are 1 answers

0
wchiquito On

Some problems in your stored procedure:

DELIMITER //

create procedure usp_testInsert (
        Matricule int,
        mot_de_passe varchar(10),
        Nom varchar(10) ,
        Prenom varchar(10)
)
begin
        INSERT INTO users (Matricule, mot_de_passe, Nom, Prenom)
        SELECT @Matricule, @mot_de_passe, @Nom, @Prenom
        -- FROM ???
        WHERE NOT EXISTS (
              SELECT 1
              /*
              FROM users (
              WHERE Matricule = @Matricule AND
              */
              FROM users
              WHERE (
                          Matricule = @Matricule AND
                          mot_de_passe = @mot_de_passe AND
                          Nom = @Nom AND
                          Prenom = @Prenom
              )
        );
end//

DELIMITER ;

UPDATE

My version, which certainly will not work, but will help you solve your problem.

DELIMITER //

DROP PROCEDURE IF EXISTS `usp_testInsert`//

CREATE PROCEDURE `usp_testInsert` (
        `_Matricule` INT,
        `_mot_de_passe` VARCHAR(10),
        `_Nom` VARCHAR(10) ,
        `_Prenom` VARCHAR(10)
)
BEGIN
        INSERT INTO `users` (`Matricule`, `mot_de_passe`, `Nom`, `Prenom`)
        SELECT `_Matricule`, `_mot_de_passe`, `_Nom`, `_Prenom`
        FROM DUAL
        WHERE NOT EXISTS (
                SELECT 1
                FROM `users`
                WHERE (
                          `Matricule` = `_Matricule` AND
                          `mot_de_passe` = `_mot_de_passe` AND
                          `Nom` = `_Nom` AND
                          `Prenom` = `_Prenom`
                )
        );
END//

DELIMITER ;