I have a list of birthdays and the year is the only part that is incorrect. I have a list of ID #s for these individuals. Is there a way to change only the year for all of these people? I was thinking something like making a table of the query results and then using an UPDATE
SET
query, but I don't know how to only change the year.
Sample included in edit. Every year needs to be decreased by 2.
Summary. You can use the DATEADD() function to change the day, month, year, quarter, dayofyear, week, weekday, hour, minute, second, milliseconds, microsecond and nanosecond as needed.
To update with the current date and time: UPDATE table_name SET date_field = CURRENT_TIMESTAMP; To update with a specific date value: UPDATE table_name SET date_field = 'YYYY-MM-DD HH:MM:SS.
MySQL displays YEAR values in YYYY format, with a range of 1901 to 2155 , and 0000 . YEAR accepts input values in a variety of formats: As 4-digit strings in the range '1901' to '2155' . As 4-digit numbers in the range 1901 to 2155 .
If all rows need to be decreased by two years, then:
UPDATE dbo.TableToUpdate SET [Date Column] = DATEADD(YEAR, -2, [Date Column]);
If all rows need to be set to a specific year (say, 2019), and the column is date
:
UPDATE dbo.TableToUpdate SET [Date Column] = DATEFROMPARTS(2019, MONTH([Date Column]), DAY([Date Column]);
If all rows need to be set to a specific year (say, 2019) and the column is not date
, you could use DATETIMEFROMPARTS
or SMALLDATETIMEFROMPARTS
, but at that point the following becomes shorter:
UPDATE dbo.TableToUpdate SET [Date Column] = DATEADD ( YEAR, -DATEDIFF(YEAR, '20190101', [Date Column]), [Date Column] );
Here's the shortest I can think of, change the year to 2050:
select dateadd(year, (2050 - year(d)), d) from x
Sample data:
create table x(d date); insert into x values ('2001-11-19'), ('2020-07-05'), ('2012-05-01');
Output:
COLUMN_0 2050-11-19 2050-07-05 2050-05-01
Live test: http://www.sqlfiddle.com/#!3/9a8b4/2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With