如何运行SQL触发器

时间:2015-06-25 18:04:07

标签: sql-server triggers

我是SQL Server 2008的新手,我编写了一个触发器,希望只执行hassubproductspdisplaytype列的更新或插入,如果它们有值且不为空。

感谢任何帮助。

CREATE TRIGGER [dbo].[hassubproductcheck] 
ON [dbo].[products]
WITH EXECUTE AS CALLER
FOR INSERT, UPDATE
AS
BEGIN
    UPDATE products 
    SET hassubproduct = LTRIM(RTRIM(hassubproduct))

    UPDATE products 
    SET spdisplaytype  = LTRIM(RTRIM(spdisplaytype))
END
GO

2 个答案:

答案 0 :(得分:1)

Something along these lines is probably more like what you want.

CREATE TRIGGER [dbo].[hassubproductcheck] ON [dbo].[products] 
WITH EXECUTE AS CALLER FOR INSERT, UPDATE 
AS BEGIN 
    Update p 
        set hassubproduct = LTRIM(RTRIM(i.hassubproduct)) 
        , spdisplaytype = LTRIM(RTRIM(i.spdisplaytype)) 
    from Products p 
    join inserted i on i.PrimaryKey = p.PrimaryKey
    where i.hassubproduct > ''
        OR i.spdisplaytype > ''

END 

答案 1 :(得分:0)

You have to use the below code to define the trigger. This will help for updated. The same way we need to create one for inserted as well.

   CREATE TRIGGER [dbo].[hassubproductcheck] ON [dbo].products]             
     AFTER UPDATE 
        AS
        INSERT INTO DBO.SAMPLE_TRIGGER
        SELECT hassubproduct, 'UPDATE(PREVIOUS)' [TABLE-UPDATE] FROM DELETED
        GO

      CREATE TRIGGER [dbo].[hassubproductcheck] ON [dbo].products]             
      AFTER UPDATE
       AS
      INSERT INTO DBO.SAMPLE_TRIGGER
        SELECT hassubproduct, 'UPDATE (LATEST)' [TABLE-UPDATE] FROM DELETED
       GO