Solved

Update Year of Datefield column with 2008 in MS SQL

Posted on 2009-05-17
4
431 Views
Last Modified: 2012-05-07
Hi,

I have this Date Field in my table in DATETIME datatype and I would like to update the year with 2008 of the entire table.
I tried this but it did not work
Update Productivity
 set RecCreateDate="2008"
where RecCreateDate is not null

It gave an Error.
Could you please give me a correct SQL statement for this
0
Comment
Question by:SriChary
  • 2
4 Comments
 
LVL 46

Expert Comment

by:tbsgadi
ID: 24406393
Hi,
DATETIME datatype holds a whole date like 1/1/2008 not just the year.

Gary
0
 

Author Comment

by:SriChary
ID: 24406408
Hi tbsgadi,

Yes DateTime datatype holds a whole date and I want to update just the year in it.

For eg: If I have a date "01/15/2003"
I want to update it to "01/15/2008"

Any options please.

Thanks
0
 
LVL 4

Assisted Solution

by:TimSledge
TimSledge earned 100 total points
ID: 24406432
See the attached code snippet.  You would need to run one iteration for each year currently in the table.
create table dbo.tblTest (TestDate DATETIME)
 
INSERT INTO dbo.tblTest (TestDate) Select '1/1/2009'
 
UPDATE dbo.tblTest
SET TestDate = DATEADD(YEAR, -1, TestDate)
WHERE DATEPART(YEAR, TestDate)=2009
 
SELECT TestDate
FROM dbo.tblTest

Open in new window

0
 
LVL 46

Accepted Solution

by:
tbsgadi earned 400 total points
ID: 24406455
UPDATE Mytable
SET RecCreateDate= DATEADD(YEAR, 2008-DATEPART(YEAR, RecCreateDate), RecCreateDate)
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I'm trying, I really am. But I've seen so many wrong approaches involving date(time) boundaries I despair about my inability to explain it. I've seen quite a few recently that define a non-leap year as 364 days, or 366 days and the list goes on. …
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question