Try this:Create Function dbo.GetIntFromDate(@DateIn datetime)Returns Int As Begin Return Cast(Replace(Convert(varchar(10), DateIn, 120), '-', '') As int)End
You could also use:Cast(Cast(Year(DateIn) As varchar(4)) + Right('0' + Cast(Month(DateIn) as varchar(2)), 2) + Right('0' + Cast(Day(DateIn) as varchar(2)), 2) as Int)
However, the performance is statistically identical:--Generate Test DataDrop Table #tableCreate Table #table (DateIn datetime)Declare @cnt intSet @cnt = 0While @cnt < 1000000 Begin Insert #table Select GetDate() + @cnt Set @cnt = @cnt + 1End--Method 1Select Cast(Replace(Convert(varchar(10), DateIn, 120), '-', '') As int)From #table/*SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 1 ms.(1000000 row(s) affected)Table '#table'. Scan count 1, logical reads 2208, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.SQL Server Execution Times: CPU time = 2141 ms, elapsed time = 8523 ms.*/--Method 2Select Cast(Cast(Year(DateIn) As varchar(4)) + Right('0' + Cast(Month(DateIn) as varchar(2)), 2) + Right('0' + Cast(Day(DateIn) as varchar(2)), 2) as Int)From #table/*SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 2 ms.(1000000 row(s) affected)Table '#table'. Scan count 1, logical reads 2208, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.SQL Server Execution Times: CPU time = 1875 ms, elapsed time = 8453 ms.*/