Sometimes you need to reserve a specified number of digits for a specific number that contains a decimal point, such as "123.123600".
This is implemented as a function in the database as follows:
Use [Database name]GO/** * * * object:userdefinedfunction [dbo]. [Avglimit] Script DATE:2016/12/29 11:30:44 * * * * **/SETAnsi_nulls onGOSETQuoted_identifier onGOCreate function [dbo].[Avglimit](@strengthNumeric -,6),@numlimit int)Returns varchar( -) as Begin Declare @avgNumeric -,6) Declare @avgStr varchar( -) Set @avg= round(@strength,@numlimit) Set @avgStr= Convert(varchar( -),@avg) if @numlimit=0 Set @avgStr = substring(@avgStr,0,Len(@avgStr)-6) if @numlimit>0 Set @avgStr = substring(@avgStr,0,Len(@avgStr)-5+@numlimit) --substring (@avgStr, 0,len (@avgStr) [email protected]Return @avgStrEnd
To illustrate:
--Keep 0 decimal places, Result: 123Select [dbo].[Avglimit](123.123600,0)--Keep 1 decimal places, Result: 123.1Select [dbo].[Avglimit](123.123600,1)--Keep 2 decimal places, Result: 123.12Select [dbo].[Avglimit](123.123600,2)--Keep 3 decimal places, Result: 123.124Select [dbo].[Avglimit](123.123600,3)--Keep 4 decimal places, Result: 123.1236Select [dbo].[Avglimit](123.123600,4)--Keep 5 decimal places, Result: 123.12360Select [dbo].[Avglimit](123.123600,5)
Note: Only 6 decimal places can be reserved, because the parameters passed when the function was created @strength numeric (6), leaving only 6 decimal places
SQL Server database implements a function that retains a specified number of decimal places