简体   繁体   中英

Automatically update a column with a special date in SQL Server

I have a table with 2 columns:

  1. ExpireDate (DateTime)
  2. IsExpired (Bit).

Is there any way that I can check automatically if ExpireDate >= Today Date and change the IsExpired column from false to true?

In fact, I would this process happened for each record in ExpireDate and I don't want check all of record manually to found what recode is expire then change IsExpired column.

You can change the IsExpired field with an update query like this:

UPDATE table SET IsExpired = 1 WHERE ExpireDate >= GetDate()

And if you want it to happen automatically you can schedule a job doing this using the SQL Server Agent.

Try following :

update yourtablename
set isexpired = 1
where ExpireDate >= convert(date,getdate())

If you want this to happen automatically, then use a view or computed column . You can add a computed column like this:

alter table YourTable
   add column isexpired as (case when ExpireDate >= getdate() then 1 else 0 end);

(You might have to drop the column first.)

The advantage of a computed column is that it never gets out of date.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM