R
R
Ramazeca2014-01-19 00:06:54
SQL
Ramazeca, 2014-01-19 00:06:54

How to create a trigger that would calculate the difference between dates in days and write this number into a field?

Good afternoon to everyone who reads me. Let me tell you right now, I am new to this.
You need to create a trigger that would calculate the difference between dates in days and write this number into a field. Actually wrote a test trigger:

create trigger trigger_set_days on guests
for insert, update
as
declare @Date1 datetime
declare @Date2 datetime
declare @TotalDays int
declare @PassportNumber varchar(50)
begin
set @Date1 = (select CheckInDate from inserted)
set @Date2 = (select CheckOutDate from inserted)
set @PassportNumber = (select PassportNumber from inserted)
if ((GETDATE()) < (@Date1))
  begin
    set @TotalDays = (select datediff(dd, @Date1, @Date2))
    update guests set TotalDays = @TotalDays where [email protected] and [email protected]
  end
else
  begin
    set @TotalDays = (select datediff(dd, GETDATE(), @Date2))
    update guests set TotalDays = @TotalDays where [email protected] and  [email protected]
  end
end

It works on insert, but when I call the stored procedure, update happens in it, it crashes with an error:
Msg 512, Level 16, State 1, Procedure trigger_set_days, Line 9
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.

Without a trigger, the update procedure works without errors. I understand what is written in the error. Explain what the problem is, why I get a lot of incomprehensible values ​​with the trigger. Is it possible to view the inserted table?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilyas Masirov, 2014-01-20
@Ilyas Masirov

The subquery returned more than one value in Force the
subquery to return only one value with WHERE and LIMIT 1.
Also correct the code in places:

set @Date2 = (select CheckOutDate from inserted)

set @PassportNumber = (select PassportNumber from inserted)

 set @TotalDays = (select datediff(dd, GETDATE(), @Date2))

set @TotalDays = (select datediff(dd, @Date1, @Date2))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question