Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change only the year of a date datatype

Tags:

sql

sql-server

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.

enter image description here

Sample included in edit. Every year needs to be decreased by 2.

like image 868
wootscootinboogie Avatar asked Apr 30 '12 18:04

wootscootinboogie


People also ask

How do I set just the year in a date in SQL?

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.

How can change year in date field in SQL Server?

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.

What is the datatype for year?

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 .


2 Answers

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]   ); 
like image 151
Aaron Bertrand Avatar answered Sep 18 '22 19:09

Aaron Bertrand


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

like image 39
Michael Buen Avatar answered Sep 18 '22 19:09

Michael Buen