如果用mysql导致语法错误

时间:2011-09-19 09:11:43

标签: mysql if-statement syntax

我需要在我的mysql触发器中使用if语句。它看起来像是:

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&lt;&gt;附近使用正确语法的服务器版本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 个答案:

答案 0 :(得分: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之后的分号(;): - )