表類型(Table Type)實現百萬級別的數據一次性毫秒級別插入 ...
使用表類型(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; }
}