在选择查询中更改数据类型

时间:2018-01-07 10:20:31

标签: sql sql-server-2008

我正在尝试将数据从一个表批量复制到另一个表。我收到错误

  

将数据类型varchar转换为数字

时出错

来源表

source table

目标表

destination table

代码:

SqlCommand cmundefined = new SqlCommand("SELECT CAST(month+'/'+day+'/'+year AS datetime) as date_time, CAST(RIGHT('0000000000'+HSCode,10) AS numeric(13,0)) as code, " +
"HSSystemDescription as name,HSUnit as unit,str(cpc) as cpc,port as port,OriginCountryName as country,HSQuantity as netweight, " +
"FOB as fob,InternalFreight as freight,Insurance as insurance,Discount as discount,OtherCharges as other,CIF as cif,Sector as sector,rate FROM rawdata WHERE TradeFlow = 'Imports' AND month=" + i.ToString(), cnn);

cnn.Open();
SqlDataReader rrundefined = cmundefined.ExecuteReader();
Conn.Open();

ses = i;
//OdbcDataReader myReader = catCMD.ExecuteReader();

SqlBulkCopy sbcx = new SqlBulkCopy("server=" + server_name + ";database=TRADE_2018;Integrated Security=SSPI");
sbcx.BulkCopyTimeout = 3600;
sbcx.ColumnMappings.Add("cpc", "cpc");
sbcx.DestinationTableName = "input";

sbcx.WriteToServer(rrundefined);

有谁知道我收到此错误的原因,以及如何更改select语句中列的数据类型?

Sample data

1 个答案:

答案 0 :(得分:0)

在rawdata表上运行此查询以查找任何非数字值:

select
    HSCode
from 
    rawdata
where
    HSCode is not null and
    try_cast(HSCode as numeric(13,0)) is null;

对HSQuantity和任何其他应该是数字的列执行相同的操作。

这将告诉您是否有非数字数据,您希望数字。