简体   繁体   English

SQL中的存储过程

[英]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. 我有一个存储过程,应该检查“ Allowed Nationality表中是否有正在添加的艺术家,但是它不起作用。 The code inserts the artist whether they are in the Allowed Nationality table or not. 该代码将插入艺术家,无论他们是否在Allowed Nationality表中。 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). 您正在尝试将字符值(NATION)放入数字变量(varRowCount)中。 What you really want is to determine the number of nations (hopefully 1) which match the new artist's nation. 您真正想要的是确定与新艺术家的国家匹配的国家(希望为1)个国家。 You also don't need the ROLLBACK statement, since the stored procedure has not done anything it needs to "undo" 您也不需要ROLLBACK语句,因为存储过程尚未执行任何需要“撤消”的操作

WIll be closed, still.... 仍将关闭。

See this line: 看到这一行:

IF (varRowCount < 0) IF(varRowCount <0)

Tell me under what conditions you think SQL Server will ever return a NEGATIVE number of rows? 告诉我您认为SQL Server在什么条件下会返回负数行?

Should be equals 0, not smaller than. 应该等于0,不小于。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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