数据转化为什么会出错

soldierluo 2012-08-09 11:47:33


select *,cast(itemName as int) num, cast(val as decimal(10,9)) scale
from CommonData.dbo.base_v_infoClass
where parentName='比例'

这样不会出错



select *,cast(itemName as int) num, cast(val as decimal(10,9)) scale
from CommonData.dbo.base_v_infoClass
where parentName='比例'

这样会出错

为什么
错误是“消息 245,级别 16,状态 1,第 2 行
在将 varchar 值 'xx商' 转换成数据类型 int 时失败。
...全文
126 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
soldierluo 2012-08-09
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]
SQL code

declare @T table([itemName] varchar(4))
insert @T
select 'xx商' union all
select '4' union all
select '5' union all
select '6'

--select *,cast([itemName] as int) from @T
/*
Conver……
[/Quote]


犀利isnumeric(itemName )=1
这个东西有用
soldierluo 2012-08-09
  • 打赏
  • 举报
回复


select cast(itemName as int) num, cast(val as decimal(10,9)) scale
from CommonData.dbo.base_v_infoClass
where parentName='比例'


不好意思,下面的代码应该是这样,少了*号
叶子 2012-08-09
  • 打赏
  • 举报
回复

declare @T table([itemName] varchar(4))
insert @T
select 'xx商' union all
select '4' union all
select '5' union all
select '6'

--select *,cast([itemName] as int) from @T
/*
Conversion failed when converting the varchar value 'xx商' to data type int.
*/
select *,cast([itemName] as int) from @T
where isnumeric(itemName )=1
/*
itemName
-------- -----------
4 4
5 5
6 6
*/

把不能转换的字符过滤掉吧
人生无悔 2012-08-09
  • 打赏
  • 举报
回复
你是不是贴错了,我怎么看到两个语句一样的

错误的原因是itemName什为'xx商',因此转换出错

你查下select * from CommonData.dbo.base_v_infoClass where itemName='xx商'

应有值的
叶子 2012-08-09
  • 打赏
  • 举报
回复
我怎么没看出来上下两段代码的区别?

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧