我想使用sqlbulkcopy方法插入新数据并更新现有数据。
我创建了将始终插入记录的方法,因此表中有可用的重复数据
string ConnectionString = Utility.GetLocalDBConnStr(dbConnModal);
DataTable dt = Utility.ToDataTable(UsersList);
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlBulkCopy bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock |
SqlBulkCopyOptions.FireTriggers | SqlBulkCopyOptions.UseInternalTransaction, null);
bulkCopy.DestinationTableName = "User";
connection.Open();
bulkCopy.WriteToServer(dt);
connection.Close();
res = true;
}
如何实现这一目标?请提出任何建议。
答案 0 :(得分:1)
请在下面找到存储过程,该存储过程将在empnre01列基础上插入数据(如果不存在)和updatedata(在表中是唯一ID)。
Create Proc usp_InsertUpdateAWSUsers
@tblUsers UsersTableType READONLY
AS
BEGIN
SET NOCOUNT ON;
UPDATE u1
SET u1.empste01= u2.empste01
,u1.[fstnme01] = u2.[fstnme01]
,u1.[surnme01] = u2.[surnme01]
,u1.[bthcnte01]= u2.[bthcnte01]
,u1.[fnce01] = u2.[fnce01]
,u1.[lane01] = u2.[lane01]
,u1.[rsnewe01] = u2.[rsnewe01]
,u1.[sxee01] = u2.[sxee01]
,u1.[bthdate01]= u2.[bthdate01]
,u1.[nate01] = u2.[nate01]
FROM Users u1
INNER JOIN @tblUsers u2
ON u1.empnre01=u2.empnre01
INSERT INTO Users
(empnre01,empste01,[fstnme01],[surnme01],[bthcnte01],[fnce01],[lane01], [rsnewe01],[sxee01],[bthdate01],[nate01])
SELECT u2.empnre01,u2.empste01,u2.[fstnme01],u2.[surnme01],u2.[bthcnte01],u2.[fnce01],u2.[lane01],u2.[rsnewe01]
,u2.[sxee01],u2.[bthdate01],u2.[nate01]
FROM @tblUsers u2
WHERE empnre01 NOT IN (SELECT empnre01 FROM Users)
END
然后您可以从C#代码中调用此SP,如下所示:
DataTable dt = List of data to be update in table.
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("usp_InsertUpdateAWSUsers"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("@tblUsers", dt);
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
res = true;
}
}