I have below sample format table structure:
CUSTOMER table
CUSTID INT,//PRIMARY KEY
CUSTDATA VARCHAR
EMPLOYEE table
EMPID INT,//PRIMARY KEY
EMPDATA VARCHAR
ITEM table
ITEMID INT,//PRIMARY KEY
CUSTID INT,//REFERENCE KEY
ITEMTYPE INT //1 FOR CUSTOMER AND 2 FOR EMPLOYEE
EMPID INT
MERGEDATA table
MERGEID INT,
CUSTDATA VARCHAR,
EMPDATA VARCHAR
ACTION VARCHAR
Above I have four tables (CUSTOMER, EMPLOYEE, ITEM and MERGEDATA), now I want to create SQL Server trigger on the ITEM table for INSERT/UPDATE/DELETE events, so whenever activity is done on the ITEM table it populates my MERGEDATA table with the action done on ITEM table.
So if any new rows get inserted into the ITEM table a new entry goes into the MERGEDATA table depending on the CUSTOMER or EMPLOYEE entries, like if there is any entry from customer it will add one entry in the ITEM table as well as in CUSTOMER table as below
CUSTOMER table
123, TESTCUSTOMER
ITEM table
1, 123, 1, 0
And same goes for Employee table too, however in the ITEM table row will be like 1, 456, 0, 2.
Now I want to write if condition in Trigger that if there is entry from CUSTOMER table
IF (ITEMTYPE == 1)
//Entry in MERGEDATA will as below
MERGEDATA table
1, 123, 0, ACTION (will depend on type of trigger event trigger if INSERT(ACTION = INS), for update (UPDATE = UPD) etc
So in short I am looking below things in trigger:
- How to write IF condition in trigger
- How to do inner joins from other table in trigger
Please suggest!!
Thanks
My suggestion would be:
create three separate triggers – one for each operation. This makes it easier to determine the
Action, and it also gives you the flexibility to turn on/off each operation individually. Furthermore, the trigger code will be smaller, easier to understand, easier to maintain.Given that design, your trigger will be dead simple:
When you create three separate triggers, just replace the
'INSERT'value forActionwith'Update'and'Delete'in those other triggers.What I have trouble with is:
Itemshould be stored into what column inMergeData?Itemor mostlyINT– your columns inMergeDataareVarchar– what kind of “conversion” do you want to apply here?For more details, see the excellent SQL Server Books Online documentation (freely available!) on
CREATE TRIGGER