Suppose my SQL Server table looks like
Col1 | Col2 | Col3 | Col4 | Col5
and my datatable looks like
Col X | Col Y | Col Z
How can I map the values from my datatable to specific columns in the SQL Server table?
The datatable contains a large number of rows so I want to avoid using row by row insert.
What would be the best way to accomplish this?
This may help you
SqlBulkCopy.WriteToServer Method (DataTable)
Copies all rows in the supplied DataTable to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.
https://msdn.microsoft.com/en-us/library/ex21zs8x(v=vs.110).aspx
Use a stored procedure with a table valued parameter.
Create a user defined table type with the same structure as your c# data table. Note that the columns of that type must match exactly to the columns of the c# data table, including the order of the columns.
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
)
Then you can create the stored procedure, where you will actually do the mapping of columns:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.