--示例--示例数据 declare @t table(ID int,数值 decimal(10,4),小数位数 int) insert @t select 1,1.0000,2 union all select 2,2.0000,3 union all select 3,3.0000,4--查询 select *,按小数位取值=left(数值,len(数值)-4+小数位数) from @t/*--测试结果ID 数值 小数位数 按小数位取值 ----------- ------------ ----------- ------------------- 1 1.0000 2 1.00 2 2.0000 3 2.000 3 3.0000 4 3.0000(所影响的行数为 3 行) --*/
select left(cast(数值 as varchar(100)),charindex('.',cast(数值 as varchar(100)))+小数位数) as 数值 from 表
create table TB(ID_1 int,數值 numeric(18,4),小數位數 int) insert into TB select 1,1.0000,2 union select 2,2.0000,3 union select 3,3.0000,4 select 數值 =left(數值,len(數值)-4+小數位數) from tb
select round(数值,小数位数)
STR(数值, LEN(数值), 小数)
select 數值=round(數值,小数位数) from 表
把zjcxc(邹建)的查询改了一下 create table t(ID int,数值 decimal(10,4),小数位数 int) insert t select 1,1.0000,2 union all select 2,2.0000,3 union all select 3,3.0000,4 --查询 SELECT *,按小数位取值=LEFT(CAST(数值 AS NVARCHAR(100)),LEN(CAST(数值 AS NVARCHAR(100)))-((SELECT MAX(小数位数) FROM T)-小数位数)) FROM T drop table t
zjcxc(邹建)大哥,还能不能根据四舍五入来决定小数的位数
select 數值=round(數值,小数位数) from 表 上面的不行改為﹕ select 數值=left(數值,len(數值)-4+小数位数) from 表
select *,cast(cast(数值 as int) as varchar)+'.'+left('0000',小数位数) from test 1 1.0000 2 1.00 2 2.0000 3 2.000 3 3.0000 4 3.0000
根据四舍五入来决定小数的位数﹕ select 數值=left(round(數值,小数位数),len(數值)-4+小数位数) from 表
declare @t table(ID int,数值 decimal(10,4),小数位数 int)
insert @t select 1,1.0000,2
union all select 2,2.0000,3
union all select 3,3.0000,4--查询
select *,按小数位取值=left(数值,len(数值)-4+小数位数)
from @t/*--测试结果ID 数值 小数位数 按小数位取值
----------- ------------ ----------- -------------------
1 1.0000 2 1.00
2 2.0000 3 2.000
3 3.0000 4 3.0000(所影响的行数为 3 行)
--*/
insert into TB select 1,1.0000,2
union select 2,2.0000,3
union select 3,3.0000,4
select 數值 =left(數值,len(數值)-4+小數位數)
from tb
create table t(ID int,数值 decimal(10,4),小数位数 int)
insert t select 1,1.0000,2
union all select 2,2.0000,3
union all select 3,3.0000,4
--查询
SELECT *,按小数位取值=LEFT(CAST(数值 AS NVARCHAR(100)),LEN(CAST(数值 AS NVARCHAR(100)))-((SELECT MAX(小数位数) FROM T)-小数位数)) FROM T
drop table t
上面的不行改為﹕
select 數值=left(數值,len(數值)-4+小数位数)
from 表
1 1.0000 2 1.00
2 2.0000 3 2.000
3 3.0000 4 3.0000
select 數值=left(round(數值,小数位数),len(數值)-4+小数位数)
from 表
恭喜zjcxc(邹建)大哥 MVP!
declare @t table(a float,b int,c decimal(10,4),d int)
insert @t select 12.2131293,3,12.2342,2select float类型=round(a,b),decimal类型=round(c,d)
from @t--结果:float类型 decimal类型
----------------------------------------------------- ------------
12.212999999999999 12.2300(所影响的行数为 1 行)