简体   繁体   中英

SQL How to update a column with data from the same table

ID START_DATE     ADD_DAYS    NEW_DATE    
------------------------------------------
1  02/02/2017     5     
2  06/24/2017     3      
3  07/14/2017     9      
4  05/19/2017     12    

I have the following table and I want to go in and update the column NEW_DATE with data that I read from the table itself. I am struggling to understand the correct MS SQL to achieve that. Any help?

UPDATE MYTABLE SET NEW_DATE = DATEADD(day, ADD_DAYS, START_DATE)

If you need to update rows using conditions, you can do for example:

UPDATE MYTABLE SET NEW_DATE = DATEADD(day, ADD_DAYS, START_DATE)
WHERE ID < 10

If you can control the schema, it might be worth adding this NEW_DATE column as a calculated column.

ALTER TABLE table_name ADD NEW_DATE as DATEADD(DAY,ADD_DAYS,START_DATE)

That way you don't need to update anything and any changes to add_days or start_date are automatically recalculated

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