首页 > 解决方案 > SQL:将数据类型 nvarchar 转换为作为联合的一部分的浮点数时出错

问题描述

我正在尝试从 2 个表创建 Mpxns 的主列表,并将此主列表连接到另一个表

Mpxns 可以是 8-13 位长(全部为数字)

在 offcoms 表中它们存储为浮点数 在 DCC 表中它们存储为 NavChar (20) 在运行状况表中它们存储为 NavChar (50)

我将 offcoms 和 DCC 故事合并到一个临时表中,然后尝试将该表中的 mpxns 链接到运行状况表,但在第 21 行获取 navchar 浮动错误 [选择 t1.pod]

我尝试在联合中将 offcoms 转换为 navchar 并尝试将 t1.pod 转换为 navchar 作为最终选择的一部分,但无法找出解决方案

原始查询

SELECT * into ##temp1 

from
(select [esme_sap_mpxn]
FROM [DOMCustomers].[Bart].[OffComs14_1]
  
  union
  
select [gsme_sap_mpxn]
FROM [DOMCustomers].[Bart].[OffComs14_1]
  
 union
  
select  MPxN
from  [DOMCustomers].[dbo].[DCC_Remote_Commissioning_Main]

Where DATE_BOCT_SENT > = '2020-11-05') as tmp


select t1.pod 
,s2h.Premise
,s2h.[Meter Health Status]

from ##temp1 as t1
left join [DOMCustomers].[Bart].MeterHealth as s2h on t1.pod=s2h.Mpxn
 
drop table ##temp1

试图在联合期间将 float 转换为 navchar

SELECT * into ##temp1 

from
(select Case when isnumeric ([esme_sap_mpxn]) =1 then cast ([Esme_sap_mpxn] as nvarchar)else 0 end as POD
FROM [DOMCustomers].[Bart].[OffComs14_1]
  
  union
  
select Case when isnumeric ([gsme_sap_mpxn]) =1 then cast ([Gsme_sap_mpxn] as nvarchar)else 0 end as POD
FROM [DOMCustomers].[Bart].[OffComs14_1]
  
 union
  
select  MPxN
from  [DOMCustomers].[dbo].[DCC_Remote_Commissioning_Main]

Where DATE_BOCT_SENT > = '2020-11-05') as tmp


select t1.pod 
,s2h.Premise
,s2h.[Meter Health Status]

from ##temp1 as t1
left join [DOMCustomers].[Bart].MeterHealth as s2h on t1.pod=s2h.Mpxn
 
drop table ##temp1

我不能使用“TRY_CONVERT”,因为它不是一个公认的内置函数名。微软 SQL Server 管理工作室 v10.0.6000.29

标签: sql-servertype-conversionunion

解决方案


你可以试试try_convert函数。除非某个值无法转换,否则您可能会通过 try_convert 函数看到这一点。这样,选择不可兑换价值并过滤掉。如果有必要,您可以为此制定不同的解决方案。

TRY_CONVERT 示例:

select [esme_sap_mpxn], TRY_CONVERT(NVARCHAR, [esme_sap_mpxn]) FROM [DOMCustomers].[Bart].[OffComs14_1]

推荐阅读