TamoDaleko
TamoDaleko

Reputation: 151

Sum up columns tsql

I want to add a varchar which looks like a number to another varchar which looks like a date

varchar A looks like this: 5

varchar B looks like this: 1999.08.22

What I want to do is add varchar A to varchar B so that it looks like this: 2004.08.22 and save it in a new column called C

UPDATE D061_15018659.dbo.T_OBJ2001 
SET C  = A + B

This add does not do a sum up and just adds it to the end.

Upvotes: 1

Views: 46

Answers (2)

Zohar Peled
Zohar Peled

Reputation: 82524

Well, what you should really do is read Aaron Bertrand's Bad habits to kick : choosing the wrong data type and refactor your database instead of keeping varchar values for ints and dates.

Assuming you can't change the database structure, you can probably convert B to date and use dateadd (Note I've had to replace the dots with empty strings in order to do the actual convert):

UPDATE D061_15018659.dbo.T_OBJ2001 
SET C = DATEADD(YEAR, CAST(A as int), CONVERT(Date, REPLACE(B, '.', ''), 112))

Upvotes: 1

Jayasurya Satheesh
Jayasurya Satheesh

Reputation: 8043

Use the Function Dateadd :

Like This :-

UPDATE D061_15018659.dbo.T_OBJ2001 
SET C  = DATEADD(YYYY,A,CAST(B AS DATE)

Upvotes: 1

Related Questions