SQL - 更新,插入或取代触发?

时间:2015-04-05 17:49:05

标签: sql sql-server-2008 triggers

如果要更新或插入表格中的某个字段的值,我想检查该值是否包含某些字符。如果确实如此,请勿插入任何内容。 我这样做了#34;而不是"触发器,但它仅适用于插入的行而不适用于更新的行。我做错了什么?我是否为此任务选择了正确的触发器?

ALTER TRIGGER trg_MakeSureOfCleanDescription
ON [dbo].[Car]
instead OF INSERT
AS
  BEGIN
      DECLARE @CharPosition_Inserted INT;

      SET @CharPosition_Inserted = 0;

      DECLARE @CharPosition_Updated INT;

      SET @CharPosition_Updated = 0;

      SELECT @CharPosition_Inserted = CHARINDEX('<', inserted.Description)
      FROM   inserted

      --select @CharPosition_Updated = CHARINDEX('<', inserted.Description) from 
      IF( @CharPosition_Inserted = 0/*and @CharPosition_Updated = 0*/ )--only if the description is html free, insert it. Otherwise don't insert nothing.
        BEGIN
            PRINT 'no html. inserting.'

            INSERT INTO Car
                        ([Year],
                         [Make],
                         [Model],
                         [Price],
                         [ExtColor],
                         [IntColor],
                         [Body],
                         [Engine],
                         [Transmission],
                         [Miles],
                         [VIN],
                         [Description],
                         [MainImage],
                         [VideoFile],
                         [StockNumber],
                         [Sold])
            SELECT [Year],
                   [Make],
                   [Model],
                   [Price],
                   [ExtColor],
                   [IntColor],
                   [Body],
                   [Engine],
                   [Transmission],
                   [Miles],
                   [VIN],
                   [Description],
                   [MainImage],
                   [VideoFile],
                   [StockNumber],
                   [Sold]
            FROM   inserted
        END
  END 

感谢。

我的代码:

1 个答案:

答案 0 :(得分:0)

您只是检查插入操作。更新的处理方式完全不同,必须在单独的触发器中处理。由于有插入的Before和After触发器,因此还有Update和Delete之前和之后的触发器。在您的情况下,您需要为更新方案创建另一个触发器。

https://technet.microsoft.com/en-us/library/ms188601%28v=sql.105%29.aspx