I have two tables called users
and formerpasswords
. In users
I have two fields: name
which is primary key
and password
. In formerpasswords
I have three fields: number
which is primary key
, name
and password
. I would like to create a trigger on users
table so if I insert pairs of values in users
table for name
and password
fields and after I update the value for password
field where name
= some of the inserts I have made in users
table, trigger fires and inserts old value of name
and password
in formerpasswords
table. How could I do that in SQL Server? I know that this can be done easily in MySQL using a before update trigger
but in SQL Server that doesn't exist so I look for a way to do this.
Thank you so much in advance.
Best Answer
Here is a functional (albeit basic) example for you. Triggers in SQL Server can be either AFTER or INSTEAD and can apply to any DML (INSERT, UPDATE or DELETE), even at the same time. Inside the scope of each trigger is a virtual table called:
These virtual tables contain every column from the base table and make modification to either the base table or other tables.
CAVEATS (or basic reminders):
FINALLY
Take care storing the passwords using a proper cryptographic library. I used VARCHAR in my example below to better illustrate the trigger logic.