black12
black12

Reputation: 45

Update year and month of date based on select statement

I have table with columns

Year | Day | CreatedDate.

I want to update CreatedDate column, so day part like CreatedDate=Day and year part in CreatedDate=Year.

I tried with datepart function in update statement but wasn't succesful.How can I do it?

Upvotes: 2

Views: 424

Answers (2)

ypercubeᵀᴹ
ypercubeᵀᴹ

Reputation: 115550

For SQL-Server 2012, that has the new function DATEFROMPARTS():

UPDATE
   TableX
SET
   CreatedDate = DATEFROMPARTS( [Year], MONTH(CreatedDate), [Day] ) ;

Upvotes: 0

Richard Deeming
Richard Deeming

Reputation: 31208

Try something like this:

UPDATE
   YourTable
SET
   CreatedDate = DateAdd(year, [Year] - DatePart(year, CreatedDate), 
      DateAdd(day, [Day] - DatePart(day, CreatedDate), CreatedDate))

Upvotes: 1

Related Questions