I have the following table:
CREATE TABLE FE_USER
(
userid int identity (321,4) CONSTRAINT userid_pk PRIMARY KEY,
username varchar(40)
);
Its corresponding history table is
CREATE TABLE FE_USER_HIST
(
userid int,
username varchar(40),
v_action varchar(50)
);
Every time an insert or update is occurred on FE_USER table, i need to input
this newly inserted record or the updated record into the history table.
How can i write the trigger in t-sql?
Here is my pseducode, but i get alot of errors:
CREATE OR REPLACE TRIGGER user_to_hist
AFTER UPDATE OR DELETE
ON FE_USER
FOR EACH ROW
DECLARE
v_action varchar(50);
BEGIN
v_action := CASE WHEN UPDATING THEN 'UPDATE' ELSE 'DELETE' END;
INSERT INTO FE_USER_HIS(userid, username, v_action)
SELECT :OLD.userid, :OLD.username, v_action
FROM .......;
END;
SQL Server does not support
CREATE OR REPLACEunfortunately. You need to use eitherCREATEorALTERdependant upon what action you are doing.Also it does not have row level triggers. All the affected rows are available to you in pseudo tables called
INSERTEDorDELETEDThe simplest way would probably be 2 separate triggers.
For Insert
And for Update
Just following up on the approach I mentioned in the comments