【问题标题】:Insert Select will not convert or cast NVARCHAR to FloatInsert Select 不会将 NVARCHAR 转换或强制转换为 Float
【发布时间】:2014-09-09 22:04:15
【问题描述】:

我正在尝试执行插入选择语句以将所有数据从一个表移动到另一个表。源表中的两个列的数据类型为 NVARCHAR,目标表的数据类型为 @987654322 @。

我曾尝试使用castconvert,但我不断收到以下消息:

将数据类型 nvarchar 转换为浮点数时出错。

代码:

INSERT INTO Destination_Table
      ([SCAC]
      ,[Date]
      ,[Orgin]
      ,[Destination Low Zip]
      ,[Destination High Zip]
      ,[Class]
      ,[Minimum Charge]
      )

SELECT [SCAC]
      ,[Date]
      ,[Origin]
      ,cast([Destination Low Zip]   as float)
      ,cast([Destination High Zip]  as float)
      ,[Class]
      ,[Minimum Charge]

  FROM source_table

【问题讨论】:

  • SELECT * FROM source_table WHERE TRY_CONVERT(float,[Destination Low Zip]) IS NULL OR TRY_CONVERT(float,[Destination High Zip]) IS NULL 有什么回报吗?

标签: select insert sql-server-2012 type-conversion


【解决方案1】:

如果没有看到数据,我会猜测列可能有一些 NULL 数据,这会抛出这个错误,所以代码应该是

INSERT INTO Destination_Table
  ([SCAC]
  ,[Date]
  ,[Orgin]
  ,[Destination Low Zip]
  ,[Destination High Zip]
  ,[Class]
  ,[Minimum Charge]
  )
SELECT [SCAC]
  ,[Date]
  ,[Origin]
  ,cast(ISNULL([Destination Low Zip],0)   as float)
  ,cast(ISNULL([Destination High Zip],0)  as float)
  ,[Class]
  ,[Minimum Charge]
FROM source_table

如果你想要 NULL,那么

INSERT INTO Destination_Table
  ([SCAC]
  ,[Date]
  ,[Orgin]
  ,[Destination Low Zip]
  ,[Destination High Zip]
  ,[Class]
  ,[Minimum Charge]
  )
SELECT [SCAC]
  ,[Date]
  ,[Origin]
  ,NULLIF(CAST(ISNULL([Destination Low Zip],0)   as float), 0)
  ,NULLIF(CAST(ISNULL([Destination High Zip],0)  as float),0)
  ,[Class]
  ,[Minimum Charge]
 FROM source_table

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多