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?

有帮助吗?

解决方案

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.

其他提示

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

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top