Reputation: 31
my experience with triggers is that it does something after an update,insert or delete. But is it possible to create a trigger to update a record automatically when its date is today? for example, I have a table with 4 columns.
StartDate EndDate Active Expired
---------------------------------------------------------------
2013-01-03 2013-01-05 True False
this is one record, what i want is to create a trigger that will update the Active
column to False
and Expired
to True
of this record when its EndDate
is = today's date (GETDATE()). How do i do this?
Upvotes: 1
Views: 1764
Reputation: 70658
To make your columns Active
and Expired
to behave the way you want, you shoould make them computed columns. The sql for those columns would be this (assuming they are DATE
columns):
--For column Active
CASE WHEN EndDate < CONVERT(DATE,GETDATE()) THEN 1 ELSE 0 END
--For Column Expired
CASE WHEN EndDate >= CONVERT(DATE,GETDATE()) THEN 1 ELSE 0 END
Upvotes: 1
Reputation: 117510
well in your case you have 2 options:
create a view (converting getdate()
to 112 to remove time):
create view <your view name>
as
select
T.StartDate,
T.EndDate,
case when T.EndDate <= convert(nvarchar(8), getdate(), 112) then 1 else 0 end as Active,
case when T.EndDate <= convert(nvarchar(8), getdate(), 112) then 1 else 0 end as Expired
from <your table> as T
And then you can select data from your view (BTW, I don't think you need both columns, because they depends on each other)
Or you can create a SQL Job to check if Date is equals today and update your columns.
Upvotes: 0
Reputation: 3272
No, as far as I know, you can't use a trigger for this situation. Triggers are executed, when data/records change. In your case, the data is not changing, only time is passing.
Look for a 'SQL job' to accomplish this task.
Upvotes: 2