简体   繁体   中英

How to perform update based on condition on respected column in MSSQL Server

I have total 8 column in table where 4 column is of date, and remaining 4 is of flag respected to date. So table structure look like this.

Column1 Column2 Column3 Column4 FlagOfColumn1 FlagOfColumn2 FlagOfColumn3 FlagOfColumn4

I have data (date) in first 4 column and Null is as default in remain 4 column. now the condition is. if date (in table in any column) is less than 8 week (compared with today's date). than i have to Set 0 to respected column. Suppose Date of Column1 is less than 8 week than i have to set 0 to FlagOfColumn1 like that. I have written simple update query which is Setting 0 to all 4 flag column that i don't want.

Use CASE :

UPDATE yourTable
SET 
     FlagOfColumn1 = CASE WHEN Column1 < DATEADD(wk, -8, GETDATE()) 
        THEN 0 ELSE FlagOfColumn1 END
    ,FlagOfColumn2 = CASE WHEN Column2 < DATEADD(wk, -8, GETDATE()) 
        THEN 0 ELSE FlagOfColumn2 END
    ,FlagOfColumn3 = CASE WHEN Column3 < DATEADD(wk, -8, GETDATE()) 
        THEN 0 ELSE FlagOfColumn3 END
    ,FlagOfColumn4 = CASE WHEN Column4 < DATEADD(wk, -8, GETDATE()) 
        THEN 0 ELSE FlagOfColumn4 END

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