Eray Geveci
Eray Geveci

Reputation: 1129

SQL copy row with a new ID after change happens

Hello i have a SQL Table which look like this:

ID      BEZEICHNUNG  PREIS        UPDATE_DATE          FLAG

1       Drake        Room         14.06.2012 16:00     0
2       Blazer       BS           12.05.2012 14:45     0

when i change a value i want to copy the row with a new id and change the flag to 1 it should look like this:

ID      BEZEICHNUNG  PREIS        UPDATE_DATE          FLAG

1       Drake        Room         11.07.2012 09:40     1
2       Blazer       BS           12.05.2012 14:45     0
3       Dune         Room         11.07.2012 09:40     0

when i change the row the update_date updates itself and set a flag to 1. how can i create an sql statement like this.

the current trigger look like this:

ALTER TRIGGER [dbo].[UPDT_DIENSTLEISTUNG]
   ON [dbo].[DIENSTLEISTUNG]
   AFTER INSERT, UPDATE
AS
BEGIN

   SET  NOCOUNT ON;

   UPDATE DIENSTLEISTUNG
      SET UPDATE_DATE    = getdate ()
    WHERE id IN (SELECT id
                   FROM inserted);


END;

Thanks in advance for your help

Upvotes: 0

Views: 381

Answers (2)

Joe G Joseph
Joe G Joseph

Reputation: 24046

Please create this trigger first and then try to update the table

CREATE TRIGGER [dbo].[UPDT_DIENSTLEISTUNG]
   ON [dbo].[DIENSTLEISTUNG]
   AFTER  UPDATE
AS

BEGIN
 SET  NOCOUNT ON;

DECLARE @MAX_ID INT;
SELECT @MAX_ID=MAX(ID) FROM DIENSTLEISTUNG;

declare @tmp Table(ID  int,     BEZEICHNUNG varchar(20), PREIS varchar(20),
     UPDATE_DATE datetime,      FLAG bit)

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

delete T from DIENSTLEISTUNG T JOIN @tmp I
ON T.ID=I.ID

INSERT INTO DIENSTLEISTUNG
SELECT @MAX_ID+ROW_NUMBER() OVER(ORDER BY ID) [ID],BEZEICHNUNG,PREIS,GETDATE(),0 
FROM INSERTED

INSERT INTO DIENSTLEISTUNG
select * from @tmp


 SET  NOCOUNT OFF;
END;

Upvotes: 2

Jānis
Jānis

Reputation: 2266

One option to do that (original row is updated, but history row is inserted) is to use SQL similar to this:

create table MyTab
(
    [id] int primary key identity,
    [name] varchar(50),
    [type] varchar(50),
    [flag] bit default 0
)

insert into MyTab([name], [type])
    Values('Drake', 'Room')
insert into MyTab([name], [type])
    Values('Blazer', 'BS')

select * from myTab

Update MyTab
    Set name = name + 'new'
Output deleted.name, deleted.type, 1
into myTab(name, type, flag)
Where name = 'Drake'

select * from myTab

Upvotes: -1

Related Questions