将字符串转换为十进制在 ms sql 服务器中不起作用
converting string to decimal not working in ms sql server
我有一个 varchar 列,样本值为:
amount
-- null value
1067.00
234.10
337.28
357.00
400.00
489.40
500.00
8000.00
我试图将此字段转换为十进制并计算总和,但我做不到。
SUM(cast(isnull(t.amount,0) as decimal(12,2))) AS TotalAmount
还有
isnull(t.amount,'0') as amount
无效。如何将varchar列转换为decimal并求和
在 CONVERT you could check your value with ISNUMERIC 函数之前是这样的:
试试这个:
create table #tmp ([Amount] varchar(50));
insert into #tmp values (NULL);
insert into #tmp values ('123.3');
insert into #tmp values ('');
insert into #tmp values (' ');
insert into #tmp values ('hello?');
insert into #tmp values ('53.23');
insert into #tmp values ('7.0');
insert into #tmp values ('3.423');
select sum(case when ISNUMERIC([Amount]) = 1 then convert(float, [Amount]) else 0 end)
from #tmp
输出:
186,953
有多种方法可以处理 NULL and/or 空字符串。这是一个使用 NULLIF;
SUM(cast(isnull(nullif(t.amount, ''),0) as decimal(12,2))) AS TotalAmount
另一种方法是使用转换后的值创建 CTE
并随后调用求和。
with ConvertedTable as
(
select cast(isnull(Amount,0) as decimal(12,2)) as [NumAmount]
from TestTable
)
select sum([NumAmount]) as [SumOfConvertedTable] from ConvertedTable
输出:
SumOfConvertedTable
-------------------
11384.78
这将在 sql server 2012 中工作:
SUM(try_convert(decimal(12,2), t.amount)) AS TotalAmount
我有一个 varchar 列,样本值为:
amount
-- null value
1067.00
234.10
337.28
357.00
400.00
489.40
500.00
8000.00
我试图将此字段转换为十进制并计算总和,但我做不到。
SUM(cast(isnull(t.amount,0) as decimal(12,2))) AS TotalAmount
还有
isnull(t.amount,'0') as amount
无效。如何将varchar列转换为decimal并求和
在 CONVERT you could check your value with ISNUMERIC 函数之前是这样的:
试试这个:
create table #tmp ([Amount] varchar(50));
insert into #tmp values (NULL);
insert into #tmp values ('123.3');
insert into #tmp values ('');
insert into #tmp values (' ');
insert into #tmp values ('hello?');
insert into #tmp values ('53.23');
insert into #tmp values ('7.0');
insert into #tmp values ('3.423');
select sum(case when ISNUMERIC([Amount]) = 1 then convert(float, [Amount]) else 0 end)
from #tmp
输出:
186,953
有多种方法可以处理 NULL and/or 空字符串。这是一个使用 NULLIF;
SUM(cast(isnull(nullif(t.amount, ''),0) as decimal(12,2))) AS TotalAmount
另一种方法是使用转换后的值创建 CTE
并随后调用求和。
with ConvertedTable as
(
select cast(isnull(Amount,0) as decimal(12,2)) as [NumAmount]
from TestTable
)
select sum([NumAmount]) as [SumOfConvertedTable] from ConvertedTable
输出:
SumOfConvertedTable
-------------------
11384.78
这将在 sql server 2012 中工作:
SUM(try_convert(decimal(12,2), t.amount)) AS TotalAmount