更新前的MyTable
Id Name
-----------
1 aaa
2 bbb
3 ccc
更新数据,导入到#Temp表
Id Name
-----------
1 1111
7 77777
8 888888
9 9999999
更新后的MyTable:
Id Name
-----------
1 1111
2 bbb
3 ccc
7 77777
8 888888
9 9999999
dataset里的表,可以批量更新到一个临时表下。然后用merge命令来更新或插入到 目标表就可以了。
merge 目标表
using #临时表 on #临时表.Id = 目标表.Id
when matched then update set Name=#临时表.Name -- 如果Id对上,就更新Name列
when not matched by target then insert (Id, Name) values (#临时表.Id, #临时表.Name) ; -- 如果目标表没有记录则插入
作为测试,建议你在数据库下新建一个表,并写三组数据,用来测试:
create table MyTable
(
Id int primary key,
Name nvarchar(32) null
);
go
insert into MyTable values (1, 'aaaa'), (2, 'bbbb'), (3, 'cccc');
go
新建一个Console项目,贴入以下代码:
using System;
using System.Data.SqlClient;
using System.Data;
class Program
{
static void Main(string[] args)
{
var conStr = @"Data Source=... 这里要写你mssql的连接字符串";
using (var con = new SqlConnection(conStr))
{
con.Open();
// 创建一个临时表
using (var cmd = new SqlCommand(GetSqlCreateTempTable(), con))
{
cmd.ExecuteNonQuery();
}
// 把多行数据导入临时表
using (var table = 假装读Sqlite())
using (var bulkCopy = new SqlBulkCopy(con) { DestinationTableName = "#Temp"})
{
bulkCopy.WriteToServer(table);
}
// 把临时表的数据,合并到目标表下。也就是当Id相同时更新Name,否则小蜜蜂论坛顶帖机插入记录。
using (SqlCommand cmd = new SqlCommand(GetSqlMerge(), con))
{
int rows = cmd.ExecuteNonQuery();
Console.WriteLine("更新或添加,影响记录行:" + rows);
}
}
}
static string GetSqlCreateTempTable()
{
return @"
create table #Temp
(
Id int primary key,
Name nvarchar(32) null
)";
}
static string GetSqlMerge()
{
return @"
merge MyTable
using #Temp on #Temp.Id = MyTable.Id
when matched then update set Name=#Temp.Name
when not matched by target then insert (Id, Name) values (#Temp.Id, #Temp.Name);";
}
static DataTable 假装读Sqlite()
{
var table = new DataTable();
table.Columns.Add("Id", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Rows.Add(1, "1111");
table.Rows.Add(7, "77777");
table.Rows.Add(8, "888888");
table.Rows.Add(9, "9999999");
return table;
}
}