How can I concat the int with a string

Kenneth Folk 21 Reputation points
2022-11-01T15:23:04.247+00:00

I get the 1 but not the text year what is wrong the data type?

FUNCTION [dbo].fndtDiff
RETURNS nvarchar
AS
BEGIN
Declare @vKey int
Declare @Dval nvarchar
Declare @d1 as DateTime
Declare @Result as nvarchar

	If @vStartTime is Not Null   
		If @vEndTime IS NULL   
			SELECT @d1 = DATEDIFF(year, @vEndTime, GETDATE()) from dbo.M_CFR_List  
		ELSE  
			SELECT @d1 = DATEDIFF(year, @vStartTime, @vEndTime) from dbo.M_CFR_List  
	--  
	  

	set @vKey = convert(int,@d1)  
	If @vKey >=1   
		set @dVal =  convert(nvarchar,@vKey )  
		set @Result = Concat(@dVal , '  year' )  
	  
	  
	RETURN @Result  

END  

GO

---- second section

Declare @vStartTime DateTIME
Declare @vEndTime DateTIME

set @vStartTime = '2017/08/25 07:00'
set @vEndTime = '2018/08/25 12:45'

SELECT dbo.fndtDiff(@vStartTime,@vEndTime) AS Result

SQL Server | Other
0 comments No comments
{count} votes

Accepted answer
  1. Yitzhak Khabinsky 26,586 Reputation points
    2022-11-01T15:47:51.13+00:00

    Hi @Kenneth Folk ,

    Please try the following T-SQL as a starting point for your function.

    SQL

    Declare @vStartTime DATETIME = '2017-08-25 07:00';  
    Declare @vEndTime DATETIME = '2018-08-25 12:45';  
      
    Declare @d1 INT  
     , @Result VARCHAR(10);  
          
    SELECT @d1 = DATEDIFF(year, COALESCE(@vStartTime,GETDATE()), COALESCE(@vEndTime, GETDATE()));  
    SET @Result = CONCAT(@d1, ' year(s)' );  
    -- Or SQL Server 2016 onwards  
    SET @Result = FORMATMESSAGE('%i year(s)', @d1);  
              
    SELECT @Result;  
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Tom Phillips 17,771 Reputation points
    2022-11-01T16:46:30.927+00:00

    You must always specify a size when defining "[n]varchar" fields. If you do not, you will get strange results.

    DATEDIFF returns an INT, not a datetime. @d1 needs to be an int.

    https://learn.microsoft.com/en-us/sql/t-sql/functions/datediff-transact-sql?view=sql-server-ver16#return-type

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.