try this. i've added 2 extra variables to make you the whole process clearer.CREATE FUNCTION [dbo].[GetId] (@Today Datetime)RETURNS char(20)with execute as callerASBEGINdeclare @seqno char(4);declare @seqno2 char(20);declare @No char(4);declare @no2 char(4)select @seqno = year(@today);--select @No=cast(cast(right(LastId, 4)as int)+1 as nchar(4)) from Idmaster;select @no = '2' --replaced your query from Idmaster tableselect @No2= cast(left(replicate('0', 4), 4-len(@No)) as char(4))select @seqno2 = @seqno + ltrim(rtrim(@no2)) + @noRETURN @seqno2ENDSELECT DBO.GETID(GETDATE())