2011-09-19 98 views
-2

我需要在我的mysql觸發器中使用if語句。它看起來像:如果與MySQL結果語法錯誤

set @countentry = (SELECT count(id) as `id` FROM `tsc_page_have_wildcard` where idwildcard=1 and idpage=5); 
IF @countentry <> 0 THEN 
    INSERT INTO `tsc_page_have_wildcard` (`idpage`, `idwildcard`) VALUES (@pageid, NEW.id); 
END IF 

通過執行觸發我得到: 錯誤代碼:1064你在你的SQL語法錯誤

;檢查對應於你的MySQL 服務器版本的手冊正確的語法使用近「IF @countentry <> 0 THEN

 INSERT INTO `tsc_page_have_wildcard` (`i' at line 1 

表結構如下:

CREATE TABLE IF NOT EXISTS `tsc_page_have_wildcard` (
    `id` int(11) NOT NULL auto_increment, 
    `idpage` int(11) NOT NULL, 
    `idwildcard` int(11) NOT NULL, 
    PRIMARY KEY (`id`), 
    KEY `idpage` (`idpage`,`idwildcard`), 
    KEY `idwildcard` (`idwildcard`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ; 

ALTER TABLE `tsc_page_have_wildcard` 
    ADD CONSTRAINT `tsc_page_have_wildcard_ibfk_1` FOREIGN KEY (`idpage`) REFERENCES `tsc_page` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, 
    ADD CONSTRAINT `tsc_page_have_wildcard_ibfk_2` FOREIGN KEY (`idwildcard`) REFERENCES `tsc_wildcard` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 

INSERT INTO `tsc_page_have_wildcard` (`id`, `idpage`, `idwildcard`) VALUES 
(1, 1, 1), 
(2, 1, 2), 
(3, 1, 3), 
(4, 1, 4), 
(5, 1, 5), 
(6, 41, 4), 
(7, 41, 5); 

有誰知道爲什麼這個如果統計不是在我的觸發器工作?

回答

1

此代碼應工作:

DELIMITER $$ 
CREATE /*!50017 DEFINER = 'root'@'localhost' */ TRIGGER `win` AFTER INSERT 
ON `tsc_page_have_wildcard` FOR EACH ROW 
BEGIN 
    SET @countentry = 
    (SELECT 
    COUNT(id) AS `id` 
    FROM 
    `tsc_page_have_wildcard` 
    WHERE idwildcard = 1 
    AND idpage = 5) ; 
    IF @countentry <> 0 
    THEN 
    INSERT INTO `tsc_page_have_wildcard` (`idpage`, `idwildcard`) 
    VALUES 
    (@pageid, NEW.id) ; 
    END IF ; 
END $$ 
DELIMITER ; 

分號(;)END IF :-)

+0

這爲我工作後。謝謝! – Briefkasten