0

I have two tables:

  • table1 has staffid
  • table2 has staffid

I want table2 staffid to be equal to table1 staffid

and when changes are made to table 1 staff id they need to change staffid in table2

How do I do this?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

3 Answers3

1

CREATE TRIGGER [dbo].[TestDb] ON [dbo].[Table1] AFTER UPDATE AS

BEGIN DECLARE @staffID int SELECT staffID = staffID FROM INSERTED

-- do something for update in table 2 END

You can use BEFORE UPDATE or AFTER UPDATE trigger to achieve your task

Here is the reference http://msdn.microsoft.com/en-us/library/ms189799.aspx

krish
  • 537
  • 2
  • 14
  • Welcome to StackOverflow: if you post code, XML or data samples, **please** highlight those lines in the text editor and click on the "code samples" button ( `{ }` ) on the editor toolbar to nicely format and syntax highlight it! – marc_s Sep 30 '13 at 06:11
1

As your first requirement is table2 staffid should be to equal table1 staffid, you can define a foreign key constraint on table2 staff id as:

ALTER TABLE table2 WITH NOCHECK
ADD CONSTRAINT FK_staffid
FOREIGN KEY(staffid)
REFERENCES table1(staffid)
ON UPDATE CASCADE

Foreign key option ‘With check’ specifies that any existing data in the foreign key table [ie Table2 ] should be validated to conform to the constraint whereas ‘WITH NOCHECK’ setting specifies that existing data is not validated to conform to the new constraint.This option can make the creation process more efficient when you know that all existing data in Table2 already conforms to the constraint, but any non-conforming records will be ignored during the creation. However, during subsequent updates to the non-conforming row, the constraint will be enforced, resulting in an error.

Also second requirement is changes made to table1 staffid should be cascaded to staffid in table2 ‘ON UPDATE CASCADE’ option should be used.

Deepshikha
  • 9,896
  • 2
  • 21
  • 21
0

If you want it to be done automatically, you need to use ON UPDATE CASCADE for the table2 staffid.

Farhan Hafeez
  • 634
  • 1
  • 6
  • 22