使用表类型(Table Type)实现百万级别的数据一次性插入
思路
1 创建表类型(TaBleType)
2 创建添加存储过程
3 使用C#语言构建一个DataTable
4 将整个Table作为参数插入
步骤1 创建表类型(TaBleType)
CREATE TYPE [dbo].[TestTableType] AS TABLE(
[SeriesNumber] [nvarchar](80) NOT NULL,
[CustomerName] [nvarchar](80) NOT NULL,
)
步骤2 创建添加存储过程
CREATE procedure [dbo].[usp_Add_RepeatDataAnalysis]
(
@TestTableType TestTableType READONLY
)
AS
BEGIN
SET NOCOUNT ON
BEGIN TRANSACTION
INSERT INTO MES_SNOriginal
(
SeriesNumber,
CustomerName
)
SELECT
SeriesNumber
,CustomerName
FROM @TestTableType
COMMIT TRANSACTION
END
步骤3 使用C#语言构建一个DataTable
public static void TestTableType()
{
DataTable dataTable = new DataTable();
dataTable.Columns.Add("SeriesNumber", typeof(string));
dataTable.Columns.Add("CustomerName", typeof(string));
DataRow dataRow = dataTable.NewRow();
dataRow["SeriesNumber"] = "SeriesNumber";
dataRow["CustomerName"] = "SeriesNumber";
AddTestTableType(dataTable);
}
步骤4 将整个Table作为参数插入
public static void AddTestTableType(DataTable dt)
{
SqlParameter[] parameters = new SqlParameter[1];
parameters[0] = new SqlParameter() { ParameterName = "TestTableType", Value = dt };//值为上面转换的datatable
ExecuteStoredProcedure("usp_Add_RepeatDataAnalysis", parameters);
}
public static void ExecuteStoredProcedure(string spName, SqlParameter[] parameterValues)
{
//自己配置数据库连接
string connectionString = "";
List<TestTableTypeDTO> resultList = new List<TestTableTypeDTO>();
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(spName, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 0;
foreach (SqlParameter p in parameterValues)
{
if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null))
{
p.Value = DBNull.Value;
}
cmd.Parameters.Add(p);
}
cmd.ExecuteNonQuery();
}
}
}
public class TestTableTypeDTO
{
public int MES_SNOriginal_UID { get; set; }
public string SeriesNumber { get; set; }
}