Click here to Skip to main content
15,910,981 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
This my script :

CASE
WHEN Users.ResignationDate IS NOT NULL THEN
DATEDIFF(YEAR,WorkStartDate,ResignationDate)
ELSE
DATEDIFF(YEAR,WorkStartDate,GETDate())END as AncinitetViaÅr,


Its give me result like this: 2

But i wanna my result look like this : 2 Years

Can someone please help or point me in the right direction. Thanks.

What I have tried:

CASE
WHEN Users.ResignationDate IS NOT NULL THEN
DATEDIFF(YEAR,WorkStartDate,ResignationDate)
ELSE
DATEDIFF(YEAR,WorkStartDate,GETDate()END as AncinitetViaÅr)+ 'Years'


But its not working
Posted
Updated 23-Feb-17 3:15am

I think you're on the right track, the query just need a little tweet. The main thing are

1. Convert the integer return from DATEDIFF to string
2. Append + ' Years' string at the end of each condition

SQL
CASE
 WHEN Users.ResignationDate IS NOT NULL THEN
  CONVERT(VARCHAR(3),DATEDIFF(YEAR,WorkStartDate,ResignationDate))+ ' Years'
 ELSE
    CONVERT(VARCHAR(3),DATEDIFF(YEAR,WorkStartDate,GETDate())) + ' Years'  
END as AncinitetViaÅr
 
Share this answer
 
Comments
Man Down 24-Feb-17 3:00am    
tnx for your help. i got one more issue with month , i use this for month and then when i look at result is look like this 2 years 556 month 22 day : CONVERT(varchar(4), DATEDIFF(YEAR, WorkStartDate, GETDATE())) + ' years '+
CAST(DATEDIFF(mm, DATEADD(yy, DATEDIFF(yy,GETDATE(),WorkStartDate), WorkStartDate), GETDATE()) AS varchar(4)) +' month '+
CAST(DATEDIFF(dd, DATEADD(mm, DATEDIFF(mm, DATEADD(yy, DATEDIFF(yy, WorkStartDate, GETDATE()), WorkStartDate), GETDATE()), DATEADD(yy, DATEDIFF(yy, WorkStartDate, GETDATE()), WorkStartDate)), GETDATE()) AS varchar(2)) +' day' end) as result
____________________________________
When i change postion WorkStartDate and GetDate() , i got another strang result ,something like this : 2 years -2 month 22 day
Bryian Tan 24-Feb-17 9:57am    
hmmm, not sure, I think that could be simplify, here is an example

DECLARE @WorkStartDate Date
SET @WorkStartDate = '9/11/2014'
SELECT
CONVERT(varchar(4), DATEDIFF(dd, @WorkStartDate, GETDATE())/365) + ' years '+

CONVERT(varchar(4), DATEDIFF(MONTH, @WorkStartDate, GETDATE()) % 12) + ' month '+

CAST(DATEDIFF(dd, DATEADD(mm, DATEDIFF(mm, DATEADD(yy, DATEDIFF(yy, @WorkStartDate, GETDATE()), @WorkStartDate), GETDATE()),
DATEADD(yy, DATEDIFF(yy, @WorkStartDate, GETDATE()), @WorkStartDate)), GETDATE()) AS varchar(2)) +' day'

You can compare the result here: Calculate Duration Between Two Dates – Results[^]
Man Down 24-Feb-17 10:03am    
thank you so much Bryian
Try google search for a change, the answer will be there.. sql format datetime to string[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900