假设我的SQL Server表看起来像
Col1 | Col2 | Col3 | Col4 | Col5
和我的数据表看起来像
Col X | Col Y | Col Z
如何映射从数据表到SQL Server表中的特定列的值?
数据表包含大量行,因此我想避免使用行插入。
完成此操作的最佳方法是什么?
使用带有表值参数的存储过程。
创建一个用户定义的表类型,其结构与C#数据表相同。请注意,该类型的列必须与C#数据表的列完全匹配,包括列的顺序。
CREATE TYPE dbo.MyTableType AS TABLE
(
ColX int, -- Must be the same data type of ColX in your c# data table
ColY nvarchar(200), -- Must be the same data type of ColY in your c# data table
ColZ float -- Must be the same data type of ColZ in your c# data table
)
然后您可以创建存储过程,实际上将在其中进行列的映射:
CREATE PROCEDURE InsertIntoMyTable
(
@TableToInsert dbo.MyTableType READONLY -- Table valued parameters must be readonly!
)
AS
INSERT INTO MyTable (Col1, Col2, Col3)
SELECT ColZ, ColX, ColY
FROM @TableToInsert
GO
这可能会帮助您
SQLBULKCOPY.WRITETOSERVER方法(DataTable)
将提供数据词中的所有行复制到SQLBulkCopy的destinationTableName属性指定的目标表中对象。
https://msdn.microsoft.com/en-us/library/ex21zs8x(v = vs.110).aspx