创建触发器时出错

发布于 2024-10-30 18:18:43 字数 472 浏览 2 评论 0原文

这是我试图创建的一个简单的触发器:

CREATE TRIGGER add_item_id BEFORE INSERT ON products 
FOR EACH ROW
BEGIN
DECLARE max_id INTEGER;
SELECT MAX(item_id) INTO @max_id FROM products;
SET NEW.item_id = @max_id + 1;
END;

我在 phpMyAdmin SQL 窗口和 mysql 提示符上都尝试了它,并得到了如下相同的错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 4 

This is a simple trigger I'm trying to create:

CREATE TRIGGER add_item_id BEFORE INSERT ON products 
FOR EACH ROW
BEGIN
DECLARE max_id INTEGER;
SELECT MAX(item_id) INTO @max_id FROM products;
SET NEW.item_id = @max_id + 1;
END;

I tried it both on phpMyAdmin SQL window and mysql prompt and get the same error as below:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 4 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

赠佳期 2024-11-06 18:18:43
delimiter //
CREATE TRIGGER add_item_id BEFORE INSERT ON products 
FOR EACH ROW
BEGIN
DECLARE max_id int;
SELECT MAX(item_id) INTO max_id FROM products;
SET NEW.item_id = max_id + 1;
END//
delimiter ;

一些注意事项:

  • 如果您声明(局部变量)max_id,请使用它。 @max_id 是一个全局变量。任何 @variable 都可以在不声明的情况下使用,但只要会话存在,它就会保留在会话中。
  • 您的代码很好,只是缺少分隔符更改。如果没有 delimiter //,MySQL 会看到 CREATE TRIGGER 语句以 ..FROM PRODUCTS; 结尾,这使其无效
delimiter //
CREATE TRIGGER add_item_id BEFORE INSERT ON products 
FOR EACH ROW
BEGIN
DECLARE max_id int;
SELECT MAX(item_id) INTO max_id FROM products;
SET NEW.item_id = max_id + 1;
END//
delimiter ;

Some notes:

  • If you declare (local variable) max_id, use it. @max_id is a GLOBAL variable. Any @variable can be used without declaring it, but it stays with the session as long as the session lives.
  • Your code is fine, you are just missing the delimiter changes. Without delimiter //, MySQL sees the CREATE TRIGGER statement ending at ..FROM PRODUCTS;, which makes it invalid
橘寄 2024-11-06 18:18:43

您还可以这样做:

CREATE TRIGGER add_item_id
  BEFORE INSERT
  ON products 
FOR EACH ROW
BEGIN
  SET NEW.item_id = 1 + ( SELECT MAX(item_id)
                          FROM products
                        ) ;
END;

注意:您可以在几乎所有 RDBMS 中声明 auto_incremented 字段。

You could also do:

CREATE TRIGGER add_item_id
  BEFORE INSERT
  ON products 
FOR EACH ROW
BEGIN
  SET NEW.item_id = 1 + ( SELECT MAX(item_id)
                          FROM products
                        ) ;
END;

Note: you can declare auto_incremented fields in almost all RDBMS.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文