放置两个查询来触发语句

时间:2019-04-09 10:17:46

标签: sql sql-server

我在触发器中添加了以下查询(创建成功),它们将按照以下顺序运行/执行,先插入然后更新?

GO

CREATE TRIGGER [FieldID]
ON [Field].[AttributeValues]
AFTER INSERT  
AS  
    INSERT INTO [Field].[Field_ElementID] (Path) 
        SELECT DISTINCT Path     
        FROM [Field].[AttributeValues] 
        WHERE Path NOT IN (SELECT Path FROM [Field].[Field_ElementID])

    UPDATE [Field].[AttributeValues] 
    SET PathID = (SELECT Id FROM [Field].[Field_ElementID] 
                  WHERE [Field].[AttributeValues].[Path] = [Field].[Field_ElementID].[Path]) 
    WHERE PathID IS NULL
GO 

谢谢, S

1 个答案:

答案 0 :(得分:0)

个人(如果我正确理解了您的SQL)会这样做,但是您的第二个查询似乎很奇怪,因为它根本没有引用inserted

CREATE TRIGGER [FieldID]
ON [Field].[AttributeValues]
AFTER INSERT
AS
BEGIN

    INSERT INTO FE ([Path])
    SELECT DISTINCT i.[Path]
    FROM inserted i
         LEFT JOIN [Field].[Field_ElementID] FE ON I.[Path] = FE.[Path]
    WHERE FE.ID IS NULL; --Needs correcting, if incorrect

    UPDATE AV
    SET PathID = FE.ID
    FROM [Field].[AttributeValues] --Seems really odd this doesn't reference inserted at all
         JOIN [Field].[Field_ElementID] FE ON AV.[Path] = FE.[Path]
    WHERE AV.PathID IS NULL;

END;