简体   繁体   中英

stored procedure in SQL

I have a stored procedure that should check if an artist being added is in the Allowed Nationality table, but it doesn't work. The code inserts the artist whether they are in the Allowed Nationality table or not. Can anyone tell me what I have done wrong?

DELIMITER //
CREATE PROCEDURE `InsertNewArtistCheck`
   (IN newLastName Char(25),
    IN newFirstName Char(25),
    IN newNationality Char(30),
    IN newDateOfBirth Numeric(4),
    IN newDateDeceased Numeric(4))
BEGIN
DECLARE varRowCount Int;
   SELECT Nation INTO varRowCount
   FROM ALLOWED_NATIONALITY
   WHERE Nation = newNationality;

   IF (varRowCount < 0)
   THEN
       ROLLBACK;
          SELECT 'Nationality Not Allowed' AS ErrorMessage;
   END IF;
   INSERT INTO ARTIST (LastName, FirstName, Nationality, 
                       DateOfBirth, DateDeceased)
               VALUES (newLastName, newFirstName, newNationality, 
                      newDateOfBirth, newDateDeceased);
   SELECT 'New artist data added to database' AS InsertStatus;
END//
DELIMITER ;

Try the following changes:

 DECLARE varRowCount Int;

       SELECT count(*) INTO varRowCount
       FROM ALLOWED_NATIONALITY
       WHERE Nation = newNationality;

       IF (varRowCount < 1)
       THEN
           ROLLBACK;
           SELECT 'Nationality '+newnationality+' not Allowed' AS ErrorMessage;
           RETURN
       END IF;

You are trying to put a character value (NATION) into a numeric variable (varRowCount). What you really want is to determine the number of nations (hopefully 1) which match the new artist's nation. You also don't need the ROLLBACK statement, since the stored procedure has not done anything it needs to "undo"

WIll be closed, still....

See this line:

IF (varRowCount < 0)

Tell me under what conditions you think SQL Server will ever return a NEGATIVE number of rows?

Should be equals 0, not smaller than.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM