一.报错信息:
Conversion failed when converting the nvarchar value ‘.’ to data type int.
翻译:转换nvarchar值“”时转换失败到数据类型int。
二.报错原因:
1.字段取数确实有问题,无法进行强制转换。
2.数据库算力不足,直接报错。
(我们下面细说2的解决方案)
三.解决方案:
解决方案一:
小部分数据(我碰到的是30w数据,字段截取后得到数字进行计算),算力不足:
添加自定义字段,Row_Number() Over(Order by 字段) FROWID:
案例如下:
select ROW_NUMBER() Over( Order by c1.FNUMBER) FRowID,c1.FNUMBER,(case when c.F_add_Text222 ='' then 1 else (convert(int,(substring(c.F_add_Text,0,CHARINDEX('*',c.F_add_Text))))*convert(int,( substring(c.F_add_Text,CHARINDEX('*',c.F_add_Text)+1,len(c.F_add_Text ))))*0.000001)/( convert(int,(substring(c.F_add_Text222,0,CHARINDEX('*',c.F_add_Text222))))*convert(int,( substring(c.F_add_Text222,CHARINDEX('*',c.F_add_Text222)+1,len(c.F_add_Text222 ))))*0.000001) end) * FREALQTY FREALQTYfrom T_PRD_INSTOCK aleft join T_PRD_INSTOCKENTRY b on a.FID = b.FIDleft join T_BD_MATERIAL c on b.FMATERIALID = c.FMATERIALIDleft join T_ENG_BOM d on c.FMATERIALID = d.FMATERIALIDleft join T_ENG_BOMCHILD e on d.FID = e.FIDleft join T_BD_MATERIAL c1 on e.FMATERIALID = c1.FMATERIALIDwhere a.FDOCUMENTSTATUS = 'C' and d.FDOCUMENTSTATUS = 'C'and a.FDATE >= dateadd(month,-6,Convert(varchar(7),'2023-03-23',120)+ '-01') and a.FDATE < Convert(varchar(7),'2023-03-23',120)+ '-01'
最终结果:成功得到数据。
解决方案二:
大部分数据计算或者算数公式过于复杂,算力不足:
添加中间临时表,分担计算压力:
案例如下:
1.临时表存在则删除
if exists (select 1 from sys.objects where name = 'theNowTable') begin drop table theNowTable end
2.创建临时表数据
select * into theNowTable from (select ROW_NUMBER() Over( Order by c1.FNUMBER) RowID,c1.FNUMBER,(case when c.F_add_Text222 ='' then 1 else (convert(int,(substring(c.F_add_Text,0,CHARINDEX('*',c.F_add_Text))))*convert(int,( substring(c.F_add_Text,CHARINDEX('*',c.F_add_Text)+1,len(c.F_add_Text ))))*0.000001)/( convert(int,(substring(c.F_add_Text222,0,CHARINDEX('*',c.F_add_Text222))))*convert(int,( substring(c.F_add_Text222,CHARINDEX('*',c.F_add_Text222)+1,len(c.F_add_Text222 ))))*0.000001) end) * FREALQTY FREALQTYfrom T_PRD_INSTOCK aleft join T_PRD_INSTOCKENTRY b on a.FID = b.FIDleft join T_BD_MATERIAL c on b.FMATERIALID = c.FMATERIALIDleft join T_ENG_BOM d on c.FMATERIALID = d.FMATERIALIDleft join T_ENG_BOMCHILD e on d.FID = e.FIDleft join T_BD_MATERIAL c1 on e.FMATERIALID = c1.FMATERIALIDwhere a.FDOCUMENTSTATUS = 'C' and d.FDOCUMENTSTATUS = 'C' and c1.FForbidStatus = 'A' and c.FForbidStatus = 'A'and a.FDATE >= dateadd(month,-6,Convert(varchar(7),'2023-03-23',120)+ '-01') and a.FDATE = dateadd(month,-6,Convert(varchar(7),'2023-03-23',120)+ '-01') and a.FDATE = dateadd(month,-6,Convert(varchar(7),'2023-03-23',120)+ '-01') and a.FDATE = dateadd(month,-6,Convert(varchar(7),'2023-03-23',120)+ '-01') and a.FDATE < Convert(varchar(7),'2023-03-23',120)+ '-01') tab
3.用临时表计算获得最终数据:
select FNUMBER,sum(FREALQTY) FREALQTY fromtheNowTable group by FNUMBER having sum(FREALQTY) >= 4200
最终结果:成功得到数据。