Solved

Update Year of Datefield column with 2008 in MS SQL

Posted on 2009-05-17
4
426 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

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

This article describes how to use the timestamp of existing data in a database to allow Tableau to calculate the prior work day instead of relying on case statements or if statements to calculate the days of the week.
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Via a live example, show how to shrink a transaction log file down to a reasonable size.

759 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now