如何将字符串数据类型从数据表转换为 DECIMAL 和 int 到 SQL 表



我正在从数据表向SQL表插入值,但出现"转换数据类型错误"。我的源文件是固定宽度的,我正在使用子字符串来获取这些值。

Source:
Amount       Name       Id            Date
-33,167.74   NHP       1,503         05/09/2017

这是我使用数据表插入SQL表的代码

private DataTable InsertDataTable()
{
DataTable datatable = new DataTable();
datatable.Columns.Add("Id", typeof(int));
datatable.Columns.Add("amount", typeof(decimal));
datatable.Columns.Add("name", typeof(string));
datatable.Columns.Add("date", typeof(datetime));
//--inserting datatable
foreach (string row in columns)
{
datarow["Id"] = Convert.ToInt32(row.Substring(51, 12).Trim().Replace(",", ""));
datarow["Amount"] = Convert.ToDecimal(row.Substring(0, 9).Trim());
datarow["date"] = Convert.ToDateTime(row.Substring(12, 18).Trim());
datarow["name"] = Convert.ToDecimal(row.Substring(20, 35).Trim());
datatable.Rows.Add(datarow);
}
}
private void InsertSqlTable()
{
DataTable finaldatatable = InsertDataTable();
//sql connection--------------------
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "[dbo].[table]";
sqlBulkCopy.ColumnMappings.Add("id", "id");
sqlBulkCopy.ColumnMappings.Add("amount", "amount");
sqlBulkCopy.ColumnMappings.Add("name", "name");
sqlBulkCopy.ColumnMappings.Add("date", "date");
}
}

我的目标表具有以下列和数据类型

id int
name string
amount money
date  datetime

我收到除字符串以外的所有数据类型的转换错误。 我的 ID 也是 1,503,我想要 1503。 你们中的任何人都可以帮助我转换为正确的数据类型并从ID中删除逗号吗? 任何帮助不胜感激!

您可以使用Regex获得所需的输出。我已经考虑过您的所有数据都将像示例数据一样格式化。

首先我用Regex来获得Id, Amount & date,之后我得到了name

正则表达式:

((-|)bd[d,./]*b)

正则表达式 101 示例。

示例 C# 代码:

using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string data = "-33,167.74   NHP       1,503         05/09/2017";
string regex = @"((-|)bd[d,./]*b)";
var matches = Regex.Matches(data, regex, RegexOptions.Multiline);
int Id = Convert.ToInt16(matches[1].Groups[0].ToString().Replace(",", ""));
decimal Amount = Convert.ToDecimal(matches[0].Groups[0].ToString());
DateTime date = Convert.ToDateTime(matches[2].Groups[0].ToString());
string name = Regex.Replace(data, regex, "").ToString().Trim();
Console.WriteLine("Id: " + Id);
Console.WriteLine("Amount: " + Amount);
Console.WriteLine("date: " + date);
Console.WriteLine("name: " + name);
}
}

DotNetFiddle 中示例的输出。

请在代码中更改以下语句:

foreach (string row in columns)
{
string data = row;
string regex = @"((-|)bd[d,./]*b)";
var matches = Regex.Matches(data, regex, RegexOptions.Multiline);
int Id = Convert.ToInt16(matches[1].Groups[0].ToString().Replace(",", ""));
decimal Amount = Convert.ToDecimal(matches[0].Groups[0].ToString());
DateTime date = Convert.ToDateTime(matches[2].Groups[0].ToString());
string name = Regex.Replace(data, regex, "").ToString().Trim();
datarow["Id"] = Id;
datarow["Amount"] = Amount;
datarow["date"] = date;
datarow["name"] = name;
datatable.Rows.Add(datarow);
}

相关内容

最新更新