简体   繁体   English

sql round函数

[英]sql round function

i need to round one decimal value to deicmal places which is passes as parameter. 我需要将一个十进制值舍入为小数位,该小数位将作为参数传递。 By doing : select round(n,@a) from tbl_Test 通过执行以下操作:从tbl_Test中选择round(n,@ a)

where n is of type decimal 18,4 and @a=2 i got result but two zeros is added at the end. 其中n是十进制18,4和@ a = 2类型,我得到了结果,但最后添加了两个零。 I want to get result without that zeros..but return value should be of ype decimal..not string. 我想得到没有那个零的结果..但是返回值应该是ype十进制..不是字符串。

Is it possible anything like : cast(round(n,@a) as decimal(18,@a))? 是否有可能像:cast(round(n,@ a)as decimal(18,@ a))?

If you want only 2 decimals, you'll need to change the scale in the definition to 2. So, exactly as you supposed: 如果只需要2个小数,则需要将定义中的小数位更改为2。因此,完全符合您的预期:

cast(round(n,@a) as decimal(18,@a)) 强制转换(舍入(n,@ a)为十进制(18,@ a))

MS SQL Server does not support the use of parameters in data type definitions. MS SQL Server不支持在数据类型定义中使用参数。 Now, "client" code does. 现在,“客户端”代码可以了。 So, an approach like this might work for you, ( either written in a db sproc with t-sql or in business layer with c# or whatever ). 因此,这样的方法可能适合您(使用t-sql在db sproc中编写,或者使用c#或其他在业务层中编写)。

use tempdb;
go
create 
--drop 
table tbl_test 
( n  decimal ( 18, 4 ) );
declare @n as decimal ( 18, 4 );
SET @n = 12.0006;
insert into tbl_test ( n ) values ( @n );
SET @n = 12.0060;
insert into tbl_test ( n ) values ( @n );
SET @n = 12.0600;
insert into tbl_test ( n ) values ( @n );
SET @n = 12.6000;
insert into tbl_test ( n ) values ( @n );

select 
    cast ( round ( n, 2 ) as decimal ( 18, 2 ) )
    , n
from tbl_test
order by n ASC

declare @var_scale integer;
set @var_scale = 2;
declare @sql nvarchar(max) = N'
select 
    cast ( round ( n, @a ) as decimal ( 18, @a ) )
    , n
from tbl_test
order by n ASC
'
set @sql = REPLACE ( @sql, '@a', @var_scale );
execute ( @sql );

But, much like Thomas said in the first comment to your question, without a pretty good explanation as to why, this would seem like pure folly. 但是,就像托马斯在对您的问题的第一条评论中所说的那样,没有很好地解释为什么,这似乎是愚蠢的。 For instance, in C#, one would, as one consumed values in field n, simply round to 2 places. 例如,在C#中,将作为字段n中的一个消耗值,简单地舍入到2位。 See this stackoverflow article. 请参阅此stackoverflow文章。 If the client is a Crystal Reports or Sql Server Reporting Services, you have the same sort of options-both have built in functions which perform the rounding for you. 如果客户端是Crystal Reports或Sql Server Reporting Services,则您具有相同的选项-都具有内置功能,可以为您执行舍入。 It may take some doing, but you can probably pass user defined scale values to them as well. 可能需要做一些事情,但是您也可以将用户定义的比例值传递给它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM