[英]Error converting datatype nvarchar to numeric
我的表数据
金额1 | 金额2 | 预期结果 |
---|---|---|
100 | 200 | 4.17% |
一种 | 500 | |
500 | 乙 | |
20 | 100 | 1.67% |
CREATE TABLE [dbo].[tblData](
[Amount1] [nvarchar](50) NULL,
[Amount2] [nvarchar](50) NULL
) ON [PRIMARY]
INSERT [dbo].[tblData] ([Amount1], [Amount2]) VALUES (N'100', N'200')
INSERT [dbo].[tblData] ([Amount1], [Amount2]) VALUES (N'A', N'500')
INSERT [dbo].[tblData] ([Amount1], [Amount2]) VALUES (N'', N'')
INSERT [dbo].[tblData] ([Amount1], [Amount2]) VALUES (N'500', N'B')
INSERT [dbo].[tblData] ([Amount1], [Amount2]) VALUES (N'20', N'100')
当我在一行上运行时,这按预期工作正常
SELECT TOP 1
Concat(CAST((cast(Amount1 AS decimal(18,4))/(cast(Amount2 AS decimal(18,4))*12))*100 AS decimal(18,2)),'%') AS Result
FROM tblData
当我在整个桌子上运行时失败
SELECT
Concat(CAST((cast(Amount1 AS decimal(18,4))/(cast(Amount2 AS decimal(18,4))*12))*100 AS decimal(18,2)),'%') AS Result
FROM tblData
返回以下错误消息。
将数据类型 nvarchar 转换为数字时出错
在执行任何操作之前检查列是否为数字:
SELECT Amount1
, Amount2
, case when isnumeric(Amount1) = 1 and isnumeric(Amount2) = 1 then
Concat(CAST((cast(Amount1 AS decimal(18,4))/(cast(Amount2 AS decimal(18,4))*12))*100 AS decimal(18,2)),'%')
else
null
end AS "Expected Result"
FROM tblData
如果您的数据中有 0,则如下所示:
SELECT Amount1, Amount2,
case when isnumeric(Amount1) = 1 and isnumeric(Amount2) = 1 and Amount2 > 0 and Amount1 > 0 then
Concat(CAST((cast(Amount1 AS decimal(18,4))/(cast(Amount2 AS decimal(18,4))*12))*100 AS decimal(18,2)),'%')
when isnumeric(Amount1) = 1 and isnumeric(Amount2) = 1 and Amount1 = 0 and Amount1 > 0 then
Concat(CAST((cast(1 AS decimal(18,4))/(cast(Amount2 AS decimal(18,4))*12))*100 AS decimal(18,2)),'%')
when isnumeric(Amount1) = 1 and isnumeric(Amount2) = 1 and Amount1 > 0 and Amount1 = 0 then
Concat(CAST((cast(Amount1 AS decimal(18,4))/(cast(1 AS decimal(18,4))*12))*100 AS decimal(18,2)),'%')
else
null
end AS "Expected Result"
FROM tblData
如果你有一个主要是数字的文本字段,但你不能依赖 then 而不是
cast(Amount1 AS decimal(18,4))
你可以使用
try_cast(Amount1 AS decimal(18,4))
如果无法完成转换,则返回 Null
我使用 try_convert 但这只是个人喜好,它们实际上是一样的
try_convert(小数(18,4),金额 1)
所以你的陈述的开头看起来像这样
case
when try_cast(Amount1 as decimal(18,4)) is not null --Numeric
and try_cast(Amount2 as decimal(18,4)) > 0 --Numeric and not zero
then Concat(CAST((try_cast(Amount1 AS decimal(18,4))/(try_cast(Amount2 AS decimal(18,4))*12))*100 AS decimal(18,2)),'%')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.