Trigger that calculates and updates age

Asked

Viewed 891 times

3

I want to create a Rigger that when firing calculates the customer’s age on each table row and updates itself.

I tried it this way:

create trigger Atualiza_Idade
on cliente
for insert,update,delete
as 

declare
@i int,
@dtnasc  datetime ,
@Idade int,
@Hoje DATETIME,
@Condicao int
Set @i=1
Set @Hoje=(SELECT GETDATE ( ))

while (@i<(select COUNT( *) from Cliente ))
begin
select @dtnasc=DataNasimento,@Idade=Idade from Cliente where id=@i;


set @Condicao = (SELECT FLOOR(DATEDIFF(DAY, @dtnasc, @Hoje) / 365.25));
if (@Condicao<>(select idade from Cliente where id=@i))
update Cliente set Idade=@Condicao where id=@i;

set @i=@i+1;

end
go

Didn’t work.

  • What error or behaviour is shown?

  • Does not perform the update.

  • You’re not telling me where to update. Ta missing clause where in the update, nay?

  • @really mutlei this was missing. but I changed and continues the same way. Thanks !

  • 1

    @Anderson Try to run the script without being on trigger and confirm that it is working. It may not be entering the if of update.

  • @Jota I did this... I really don’t think it’s entering if. Because SQLSERVER returns:"Command(s) completed successfully." But nothing happens....

Show 1 more comment

1 answer

4


It won’t. Missed the use of the special table INSERTED, which precisely indicates the set of altered records of the table in question.

What you really want is a Stored Procedure. Trigger is only activated when some record is activated. In this case, it would be:

create procedure Atualiza_Idade
as 

    declare
    @i int,
    @dtnasc  datetime ,
    @Idade int,
    @Hoje DATETIME,
    @Condicao int

    SELECT @i = MIN(ID) FROM Cliente
    Set @Hoje=(SELECT GETDATE ( ))

    while (@i<(select COUNT( *) from Cliente ))
    begin
    select @dtnasc=DataNasimento,@Idade=Idade from Cliente where id=@i;

    set @Condicao = (SELECT FLOOR(DATEDIFF(DAY, @dtnasc, @Hoje) / 365.25));
    if (@Condicao<>(select idade from Cliente where id=@i))
    update Cliente set Idade=@Condicao where id=@i;

    set @i=@i+1;

end
go
  • Perfectly Gypsy.... But there is still a detail that is preventing the functioning. The parameter . @i is receiving the value 1. But if there is no ID 1 it will not run select . @dtnasc=Dating,. @Age=Age from Client Where id=. @i;. thus the parameters . @dtnasc and . @Age do not receive value. I noticed this by doing a debug... I still need help. rsrsrss

  • 1

    @Anderson So you trade for SELECT @i = MIN(ID) FROM Cliente. I’ll update the answer.

  • 2

    Age should not be recorded field but a calculated field.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.