SQL Server database implements a function that retains a specified number of decimal places

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.