-1

我是 MySql 的新手。我创建了一个程序:

DELIMITER $$

CREATE PROCEDURE `sampledb`.`InsertSample`
(
    IN aName VARCHAR(20),
    IN aVersion VARCHAR(10),
    IN pName VARCHAR(50),
    OUT InsertStatus VARCHAR(30)
)
BEGIN
IF NOT EXISTS(SELECT st.AName FROM sampletable st WHERE st.AName = aName)
    INSERT INTO sampletable(AName, AVersion, PName) 
    VALUES(aName, aVersion, pName)
    SET InsertStatus = 'Success'
ELSE
    SET InsertStatus = 'Already exists!'
END IF
END$$

DELIMITER $$;

我也尝试了其他插入方式:

 INSERT INTO sampletable (aName, aVersion, pName)

这两次,我都收到了这个错误:

Error Code : 1064
You have an error in your SQL syntax; check the manual that 
corresponds to your MySQL server version for the right syntax ..

我正在使用 MySql 5.0.51b-community-nt

4

2 回答 2

0

您的代码缺少分号 ( ;)。

改变

BEGIN
IF NOT EXISTS(SELECT st.AName FROM sampletable st WHERE st.AName = aName) THEN
    INSERT INTO sampletable(AName, AVersion, PName) 
    VALUES(aName, aVersion, pName)
    SET InsertStatus = 'Success'
ELSE
    SET InsertStatus = 'Already exists!'
END IF
END$$

DELIMITER $$;

BEGIN
IF NOT EXISTS( SELECT st.AName FROM sampletable st WHERE st.AName = aName ) THEN
    INSERT INTO sampletable( AName, AVersion, PName ) 
    VALUES( aName, aVersion, pName );
    SET InsertStatus = 'Success';
ELSE
    SET InsertStatus = 'Already exists!';
END IF;
END;
$$

DELIMITER ;

它应该可以工作。

于 2012-07-06T09:45:44.167 回答
0

试试这个:

DELIMITER $$

CREATE PROCEDURE `sampledb`.`InsertSample`
(
    IN aName VARCHAR(20),
    IN aVersion VARCHAR(10),
    IN pName VARCHAR(50),
    OUT InsertStatus VARCHAR(30)
)
BEGIN

IF NOT EXISTS(SELECT st.AName FROM sampletable st WHERE st.AName = aName) THEN
    INSERT INTO sampletable(AName, AVersion, PName) VALUES(aName, aVersion, pName);
    SET InsertStatus = 'Success';
ELSE SET InsertStatus = 'Already exists!';

END IF;

END$$

DELIMITER $$;

您需要确保标记每一行的结尾,并且您的语句中缺少 THEN 子句

于 2012-07-06T09:52:31.697 回答