在ms sql server中触发问题?

时间:2012-03-28 11:53:17

标签: sql sql-server sql-server-2008 triggers ssis

IF EXISTS (SELECT name FROM sysobjects WHERE name = 'myTrigger' AND type = 'TR')
BEGIN
    DROP TRIGGER myTrigger
END
GO
go
create trigger myTrigger
on mytable_backup
instead of insert
as
begin
  declare @seq int
  select @seq = seq from inserted 
  if exists (select * from mytable_backup where seq= @seq) begin
      delete from mytable_backup where seq=@seq
  end
  insert into mytable_backup
  select * from inserted
end
go

如果seq列重复,我已经编写了此触发器,以便在插入时检查seq,如果seq未退出,请使用相同的seq更新前一行。 1}}。

在ssis包中我使用OLEDB表(Mytable)作为包含的源。

Name,Age,Seq
Gauraw,30,1
Gauraw,31,1
Kiran,28,3
Kiran,29,3
kiran,28,3
Venkatesh,,4
Venkatesh,28,4

现在我将此表加载到OLEDB目标(Mytable_backup)作为目标。 我想输出为。

Gauraw,31,1
kiran,28,3
Venkatesh,28,4

但是我将Mytable的所有记录都记录到Mytable_backup

我的触发器有什么问题?

2 个答案:

答案 0 :(得分:1)

我认为这个触发器只会占据第一行并将其与现有行进行比较。如果我理解你想做什么,你可以轻松退出:

IF EXISTS (SELECT name FROM sysobjects WHERE name = 'myTrigger' AND type = 'TR')
BEGIN
    DROP TRIGGER myTrigger
END
GO
go
create trigger myTrigger
on mytable_backup
instead of insert
as
begin
insert into mytable_backup
select 
    * 
from 
    inserted
WHERE NOT EXISTS
    (
        SELECT
            NULL
        FROM
            mytable_backup AS mytable
        WHERE
            inserted.seq=mytable.seq
    )
end
go

修改

所以我发现了发生了什么。如果您将所有行一起插入,inserted包含所有行..抱歉我的错误。如果您的数据中有重复项,则您的示例不会显示要选择的内容。我选择了年龄最大的那个(不知道你的要求是什么)。这是一个完整示例的更新

表格结构

CREATE TABLE mytable_backup
(
    Name VARCHAR(100),
    Age INT,
    Seq INT
)
GO

<强>触发

create trigger myTrigger
on mytable_backup
instead of insert
as
begin
;WITH CTE
AS
(
    SELECT
        ROW_NUMBER() OVER(PARTITION BY inserted.Seq ORDER BY Age) AS RowNbr,
        inserted.*
    FROM
        inserted
    WHERE NOT EXISTS
    (
        SELECT
            NULL
        FROM
            mytable_backup
        WHERE
            mytable_backup.Seq=inserted.Seq
    )
)
insert into mytable_backup(Age,Name,Seq)
SELECT
    CTE.Age,
    CTE.Name,
    cte.Seq
FROM
    CTE
WHERE
    CTE.RowNbr=1
end
GO

插入测试数据

INSERT INTO mytable_backup
VALUES
    ('Gauraw',30,1),
    ('Gauraw',31,1),
    ('Kiran',28,3),
    ('Kiran',29,3),
    ('kiran',28,3),
    ('Venkatesh',20,4),
    ('Venkatesh',28,4)

SELECT * FROM mytable_backup

删除数据库对象

DROP TRIGGER myTrigger
DROP TABLE mytable_backup

答案 1 :(得分:1)

您的原始代码有两个缺陷:

  1. 它假定一次只插入一条记录。

  2. 您在mytable_backup中的插入发生在if条件之外。该插入将每次执行。