SQL Server retains decimals (cont. a)

Source: Internet
Author: User

After writing the last article, there are friends to give out other ideas, I in the summary in this blog.

Idea one: Convert the output to a string (this is also the idea given in the previous article)

1 1 SELECT   Case   when @a % @b = 0   Then CAST(@a / @b  as VARCHAR( -)) 2 2               ELSE  CAST(CAST(@a * 1.0 / @b  as DECIMAL(Ten,4)) as VARCHAR( +))END '12/5',3 3          Case   when @c % @d = 0   Then CAST(@c / @d  as VARCHAR( -))4 4               ELSE  CAST(CAST(@c * 1.0 / @d  as DECIMAL(Ten,4)) as VARCHAR( +))END '12/3'
View Code

Idea two: Use the Replace () function to determine the form after the decimal point

1 DECLARE @a INT,@b INT,@c INT,@d INT2 SET @a    =  A3 SET @b  = 54 SET @c =  A5 SET @d = 3        6 SELECT REPLACE(CAST(@a * 1.0 / @b  as DECIMAL(Ten,4)),'. 0000',"')'12/5',7        REPLACE(CAST(@c * 1.0 / @d  as DECIMAL(Ten,4)),'. 0000',"')'12/3'
View Code

Idea three: Use the round () function to determine whether the result after rounding is equal to the original result

1 DECLARE @a INT,@b INT,@c INT,@d INT2 SET @a    =  A3 SET @b  = 54 SET @c =  A5 SET @d = 3    6 SELECT       Case    when ROUND(@a * 1.0 / @b,0)= @a * 1.0 / @b   Then  CAST(@a / @b  as VARCHAR( -))7                  ELSE CAST(CAST(@a * 1.0 / @b  as DECIMAL(Ten,4)) as VARCHAR( +))END '12/5',8                  9            Case    when ROUND(@c * 1.0 / @d,0)= @c * 1.0 / @d  Then  CAST(@c / @d  as VARCHAR( -)) Ten                  ELSE CAST(CAST(@c * 1.0 / @d  as DECIMAL(Ten,4)) as VARCHAR( +))END '12/3'          
View Code

The operation results of the above three ideas are as follows:

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.