Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
mcbtiger
Starting Member
4 Posts |
Posted - 2010-05-09 : 14:14:07
|
| I have littel problem in creating triggeri create table Employees which include four filed EmpName Sex Age RemarkAmylee Female 45 Over Age EmpJack Male 19 Young Age Empi create trigger which automaticlly give Remarkcreate trigger emp on employeesfor insertasif (select age from inserted)>20beginupdate employeesset status=Over Age Emp’where age >=20endElseif (select age from inserted)<20beginupdate employeesset status='Young Age Emp'where age <=20endThis trigger not Work it update all data filed it give Remark"Over age Emp" for all emp which have under age 20 and over 20 it give same remarkMuhammadali |
|
|
jeffw8713
Aged Yak Warrior
819 Posts |
Posted - 2010-05-09 : 15:43:03
|
| The problem is your IF statement. If you have more than one row in the inserted table, the sub-query is going to fail. You do not need the check - you can update everything you need to with the following:UPDATE emp SET Status = CASE WHEN Age > 20 THEN 'Over Age Emp' WHEN Age <= 20 THEN 'Young Age Emp' END FROM dbo.Employees emp INNER JOIN inserted i ON i.{pk column} = emp.{pk column};However, I wouldn't use a trigger to update this column. I would create the column as a computed column on the table and use a CASE expression to return the appropriate value based upon the Age. No reason to have the trigger in the first place. |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2010-05-10 : 13:22:47
|
| why should you need a trigger for this? isnt a computed column enough? just make status column as computed with below definitionstatus AS CASE WHEN age <=20 THEN 'Young Age Emp' ELSE 'Over Age Emp' END------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|
|