MySQL函数定义 - ' BEGIN' (begin)不是此位置的有效输入

时间:2015-11-04 04:56:17

标签: mysql function mysql-workbench

我从MySQL的教科书中逐字输入。

红色X表示BEGIN行上的错误,其中包含文字' BEGIN' (开始)不是此位置的有效输入。

使用的数据库是View Ridge Gallery。代码有任何明显的问题吗?

DROP FUNCTION IF EXISTS InsertCustomerAndInterests;

DELIMITER $$

CREATE FUNCTION InsertCustomerAndInterests
   (
newLastName         Char(25),
newFirstName        Char(25),
newAreaCode         Char(3),
newPhoneNumber      Char(8),
newEmail            Varchar(100),
newNationality      Char(30)
)
  BEGIN

DECLARE varRowCount     Int;
DECLARE varArtistID     Int;
DECLARE varCustomerID   Int;
DECLARE done            Int DEFAULT 0;
DECLARE AristCursor     CURSOR FOR
        SELECT      AristID
        FROM        ARTIST  
        WHERE       Nationality=newNationality;
DECLARE continue        HANDLER FOR NOT FOUND SET done = 1;

#Check to see if Customer already exists in datebase
SELECT Count(*) INTO varRowCount
FROM    CUSTOMER 
WHERE   LastName = newLastName
    AND FirstName = newFirstName
    AND AreaCode = newAreaCode
    AND PhoneNumber = newPhoneNumber
    AND Email = newEmail;
#IF (varRowCount > 0 ) THEN Customer already exists
IF (varRowCount > 0 ) 
    THEN 
        ROLLBACK; 
        SELECT 'Customer already exists';
    END IF;

#IF (varRowCount = 0 ) THEN Customer does not exist.
#Insert new Customer data
IF (varRowCount = 0)
    THEN 
        INSERT INTO CUSTOMER (LastName, FirstName, AreaCode, PhoneNumber, Email)
        VALUES (newLastName, newFirstName, newAreaCode, newPhoneNumber,        newEmail);
    #Get new CustomerID surrogate key value 
    SET varCustomerID = LAST_INSERT_ID();
#Create intersection record for each appropriate Arist.

OPEN AristCursor;
REPEAT
    FETCH ArtistCursor INTO varArtistArtistID;
        IF NOT done THEN
            INSERT INTO CUSTOMER_ARTIST_INT (ArtistID, CustomerID)
                VALUES (varArtistID, varCustomerID);
            END IF;
UNTIL done END REPEAT;
CLOSE ArtistCursor;
SELECT 'New customer and artist interest data added to database.'
    AS InsertCustomerAndInterestsResults;

END IF;
END

$$
DELIMITER ;

2 个答案:

答案 0 :(得分:2)

您需要在开始之前添加返回类型,并且必须从函数返回值。

 DELIMITER $$

    DROP FUNCTION IF EXISTS `InsertCustomerAndInterests`$$

    CREATE  FUNCTION `InsertCustomerAndInterests`(
    newLastName         CHAR(25),
    newFirstName        CHAR(25),
    newAreaCode         CHAR(3),
    newPhoneNumber      CHAR(8),
    newEmail            VARCHAR(100),
    newNationality      CHAR(30)
    ) RETURNS INT(11) # you missed return type here.
    BEGIN
    DECLARE done INT DEFAULT 0;


            RETURN done; # must match with return type
    END$$

    DELIMITER ;

答案 1 :(得分:0)

由于所有函数都需要返回值和返回类型,因此在声明参数后缺少RETURNS子句。见CREATE FUNCTION