当我尝试在表中插入内容时,为什么会一直收到此错误消息

时间:2015-04-27 01:34:10

标签: sql sql-server triggers insert

以下是我必须回答的问题:

  1. 创建名为Products_INSERT的触发器,如果​​该列的值为null,则会触发Products表的DateAdded列的当前日期。 使用适当的INSERT语句测试此触发器。
  2. 以下是我的代码:

        CREATE TRIGGER Products_INSERT
            ON Products
            AFTER INSERT
        AS
            UPDATE Products
            SET DateAdded = GETDATE()
            WHERE DateAdded IS NULL OR
                  DateAdded IN (SELECT DateAdded FROM inserted);
    

    这是我的插入声明:

        INSERT INTO Products
        VALUES (4, 'LK-5300', 'Likeable Keyboard 5300',
        'This keyboard is so cool, you just might flip!',
        699.99, 30.00, NULL)
    

    以下是我不断得到的错误:

        Msg 547, Level 16, State 0, Line 1
        The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Products__Catego__145C0A3F". The conflict occurred in database "MyGuitarShop", table "dbo.Categories", column 'CategoryID'.
        The statement has been terminated.
    

    我知道错误与外键有关,但我并不完全确定。任何帮助将不胜感激。

    编辑:

        CREATE TABLE Products (
          ProductID         INT            PRIMARY KEY   IDENTITY,
          CategoryID        INT            REFERENCES Categories (CategoryID), 
          ProductCode       VARCHAR(10)    NOT NULL      UNIQUE,
          ProductName       VARCHAR(255)   NOT NULL,
          Description       TEXT           NOT NULL,
          ListPrice         MONEY          NOT NULL,
          DiscountPercent   MONEY          NOT NULL      DEFAULT 0.00,
          DateAdded         DATETIME                     DEFAULT NULL
          );
    

    这是Products表

2 个答案:

答案 0 :(得分:0)

感谢@Turophile这是我在阅读你的帖子后最终对​​我的INSERT语句所做的事情:

    INSERT INTO Products (CategoryID, ProductCode, ProductName, Description, ListPrice,DiscountPercent, DateAdded)
    VALUES (44444, 'LK-5300', 'Likeable Keyboard 5300',
    'This keyboard is so cool, you just might flip!',
     699.99, 30.00, NULL)

答案 1 :(得分:-1)

您的INSERT应该是:

INSERT INTO Products
  (   CategoryID,
      ProductCode,
      ProductName,
      Description,
      ListPrice,
      DiscountPercent,
      DateAdded
   )   
    VALUES (4, 'LK-5300', 'Likeable Keyboard 5300',
    'This keyboard is so cool, you just might flip!',
    699.99, 30.00, NULL)

您的INSERT缺少一个值进入ProductID列,因为它是自动生成的,因为它被定义为IDENTITY但要使其起作用,您需要命名列,省略{{ 1}}。