1

我对更新触发器的编程有疑问。我想创建一个触发器,将我编辑的行复制到具有新数据和新 ID 的新行中。旧行应该是相同的,只是将标志从 0 更改为 1。

该表如下所示:

ID      Artikelname  PREIS        UPDATE_DATE          FLAG
1       Tomatoe      3            14.06.2012 16:00     0
2       Apple        1,5          12.05.2012 14:45     0

当我更改第一行的价格时,表格应如下所示:

ID      Artikelname  PREIS        UPDATE_DATE          FLAG
1       Tomatoe      3            14.06.2012 16:00     1
2       Apple        1,5          12.05.2012 14:45     0
1       Tomatoe      2            13.07.2012 10:45     0

到目前为止,这是我的触发器:

USE [TestDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[Produkt_Update]
ON [dbo].[Produkt]
AFTER UPDATE
AS
BEGIN
    SET NOCOUNT ON
    DECLARE @ID int
    DECLARE @Artikelname nvarchar(50)
    DECLARE @Preis numeric
    DECLARE @Flag numeric
    DECLARE @max_id int

    SET @ID = (SELECT ID FROM inserted)
    SET @Artikelname = (SELECT Artikelname FROM inserted)
    SET @Preis = (SELECT Preis FROM inserted)
    SET @Flag = (SELECT Flag FROM inserted)
    SET @max_id = (SELECT MAX(ID) from dbo.Produkt)


    SET IDENTITY_INSERT dbo.Produkt ON
    INSERT INTO dbo.Produkt
    (ID,Artikelname,Preis)
    values (@max_id+1,@Artikelname,@Preis)
    SET IDENTITY_INSERT dbo.Produkt OFF

    UPDATE dbo.Produkt
    SET Flag = 1
    WHERE ID=@ID
END

使用触发器,我可以创建新行,但第一行窗台上的价格会发生变化。我不知道如何处理这个。请问你能帮帮我吗?

4

3 回答 3

4

请试试这个,让我知道

CREATE TRIGGER [dbo].[Produkt_Update]
   ON [dbo].[Produkt]
   AFTER  UPDATE
AS
BEGIN
 SET  NOCOUNT ON;

    DECLARE @MAX_ID INT;
    SELECT @MAX_ID=MAX(ID) FROM [Produkt];

    declare @tmp Table(ID  int,     Artikelname  varchar(200),
    PREIS varchar(200),UPDATE_DATE datetime,      FLAG bit)

    insert into @tmp
    select ID,Artikelname,PREIS,UPDATE_DATE,1 [flag] from deleted;

    delete T from [Produkt] T JOIN @tmp I
    ON T.ID=I.ID

SET IDENTITY_INSERT   [Produkt] ON
INSERT INTO [Produkt] (ID,Artikelname,PREIS,UPDATE_DATE,FLAG)
SELECT @MAX_ID+ROW_NUMBER() OVER(ORDER BY ID) [ID],Artikelname,PREIS,GETDATE(),0 
FROM INSERTED
union all
select * from @tmp

 SET IDENTITY_INSERT dbo.Produkt OFF
 SET  NOCOUNT OFF;
END;
于 2012-07-13T09:08:26.780 回答
0

您需要从已删除的表中插入价格(preis),而不是插入的表

于 2012-07-13T09:13:05.927 回答
-1

代替

 SET @ID = (SELECT ID FROM inserted) 

SET @ID = (SELECT ID FROM deleted) 
于 2012-07-13T08:58:28.837 回答