When I am creating a trigger for finding the grade of Student based on its AVG (SQL Server) -
create trigger grade123 on student after insert begin update student set grade = case when avg > 75 'firstclass' when avg > 50 , avg < 75 'second class' when avg > 35 , avg < 60 'third class' else 'fail' end
i error:
msg 102, level 15, state 1, procedure grade123, line 11
incorrect syntax near 'end'
kindly me out
you have begin trigger, need add end. word avg reserved word need escape it.
create trigger grade123 on student after insert begin update student set grade = case when [avg] > 75 'first class' when [avg] > 50 , [avg] <= 75 'second class' when [avg] > 35 , [avg] < 60 'third class' else 'fail' end end
however @marc_s said trigger updating every row of table every time row inserted. should add lookup inserted
special table available triggers shows records modified
assuming students looks like
create table students ( student_id int identity(1,1), grade varchar(10), [avg] int ) go
then
create trigger grade123 on students after insert begin update students set grade = case when [avg] > 75 'first class' when [avg] > 50 , [avg] <= 75 'second class' when [avg] > 35 , [avg] < 60 'third class' else 'fail' end student_id in (select student_id inserted) end
for loop if..else (although never use in production showing like)
set nocount on; declare @students table ( ident int identity(1,1), student_id int, [avg] int ) insert @students (student_id, [avg]) select student_id, [avg] students declare @table_count int = (select coalesce(count(ident),0) @students) declare @counter int = 1 declare @avg int while (@table_count > 0 , @counter <= @table_count) begin select @avg = [avg] @students ident = @counter if (@avg > 75) update students set grade = 'first class' student_id = @counter else if (@avg > 50 , @avg <= 75) update students set grade = 'second class' student_id = @counter else if (@avg > 35 , @avg < 60) update students set grade = 'third class' student_id = @counter else update students set grade = 'fail' student_id = @counter set @counter += 1; end
Comments
Post a Comment