所以我设置了一个应用程序来导入CSV文件。它创建了一个数据表和一个临时的sql表。代码读取CSV并将其放入数据表中,然后将其批量导入到临时表中,现在只需将其复制到生产表中即可。为了我的目的,我需要它,以便当导入.csv文件并且有空字符串时,它们将被跳过并且不在生产数据库中插入或更新,只插入/更新csv中存在的内容(除了空字符串课程)。
所以例如说我第一次去导入我只是简单地导入了以下网站信息:
PDW0033B50D3,东北办事处,246 Western Blvd
然后再说我要更新位置的地址,所以我重新导入一个只有必要字段的csv文件。
PDW0033B50D3 ,, 290 Western Blvd
现在,代码将在数据库中为空行添加第二行的空字符串,因此Northeast office将变为数据库中的空白/空字符串。我怎么做到这样,当csv中有一个空字符串时,它会通过我的sql查询跳过?
这是我的代码:
public void btnBulkSite_click(object sender, EventArgs e)
{
//Save File
if (FileUpLoad1.HasFile)
{
FileUpLoad1.SaveAs(@"C:\temp\" + FileUpLoad1.FileName);
btnBulkSite.Text = "File Uploaded: " + FileUpLoad1.FileName;
}
else
{
btnBulkSite.Text = "No File Uploaded.";
}
//Create Temporary Table
string TmpTable = "CREATE TABLE #TMPBULK (SERVER_ID VARCHAR(13), SITE_NAME VARCHAR(50), SITE_ADDRESS VARCHAR(50))";
//Create DataTable
DataTable tblcsv = new DataTable();
tblcsv.Columns.Add(new DataColumn("SERVER_ID", typeof(string)));
tblcsv.Columns.Add(new DataColumn("SITE_NAME", typeof(string)));
tblcsv.Columns.Add(new DataColumn("SITE_ADDRESS", typeof(string)));
//Read in CSV File
System.IO.StreamReader stream = new System.IO.StreamReader(FileUpLoad1.PostedFile.InputStream);
string ReadCSV = stream.ReadToEnd();
foreach (string csvRow in ReadCSV.Split('\n'))
{
if (!string.IsNullOrEmpty(csvRow))
{
tblcsv.Rows.Add();
int count = 0;
foreach (string FileRec in csvRow.Split(','))
{
tblcsv.Rows[tblcsv.Rows.Count - 1][count] = FileRec;
count++;
}
}
}
//SQL CON
string conString = ConfigurationManager.ConnectionStrings["css"].ConnectionString;
using (SqlConnection con2 = new SqlConnection(conString))
{
con2.Open();
//Execute the command to make a temp table
SqlCommand cmd = new SqlCommand(TmpTable, con2);
cmd.ExecuteNonQuery();
using (BulkOperation bulk = new BulkOperation(con2))
{
bulk.DestinationTableName = "#TMPBULK";
bulk.BulkInsert(tblcsv);
}
//Copy Data from Temp Table to Prod Table
string mergeSql = "merge into SITE_INFO as Target " +
"using #TMPBULK as Source " +
"on " +
"Target.SERVER_ID=Source.SERVER_ID " +
"and Target.SITE_NAME = Source.SITE_NAME " +
"when matched then " +
"update set Target.SITE_ADDRESS=Source.SITE_ADDRESS " +
"when not matched then " +
"insert (SERVER_ID,SITE_NAME,SITE_ADDRESS) values (Source.SERVER_ID,Source.SITE_NAME,Source.SITE_ADDRESS);";
cmd.CommandText = mergeSql;
cmd.ExecuteNonQuery();
cmd.CommandText = "drop table #TMPBULK";
cmd.ExecuteNonQuery();
}
}
答案 0 :(得分:0)
尝试从
更改您的SETupdate set Target.SITE_ADDRESS=Source.SITE_ADDRESS
到
update set Target.SITE_ADDRESS=IF(Source.SITE_ADDRESS='',Target.SITE_ADDRESS,Source.SITE_ADDRESS)
和SITE_NAME类似。