问题
I have a DataTable
which is generated from .xls table.
I would like to store this DataTable
into an existing table in SQL Server database.
I use SqlBulkCopy
to store rows which have unique PK.
Problem is, I also have other rows which have same PK as SQL Server table but contain cells with different value compared to SQL Server table.
In short:
Let's say in my DataTable
I have a row like this:
id(PK) | name | number
005 | abc | 123
006 | lge | 122
For my SQL server I have sth like this;
id(PK) | name | number
004 | cbs | 345
005 | lks | 122
Now you see the row 006 can be uploaded straight away into SQL Server using SqlBulkCopy
. On the other hand the row 005 can't be inserted using it since SQL server table contains row with identical PK.
Now I tried to manually extract the row. Extract each single cell into an ArrayList then generate an UPDATE Table statement afterwards. However this method seems to be unfeasible as I have so many rows to process.
I am looking for a better method to achieve this goal.
Any help is appreciated.
Thank's
回答1:
Use the below code:
C# Side code for reading data from DataTable and preparing the XML data:
DataTable dt = new DataTable();
StringBuilder sb = new StringBuilder();
sb.Append("<R>");
for (int i = 0; i < dt.Rows.Count; i++)
{
sb.Append("<C><ID>" + dt.Rows[0].ToString() + "</ID>");
sb.Append("<N>" + dt.Rows[1].ToString() + "</N>");
sb.Append("<I>" + dt.Rows[2].ToString() + "</I></C>");
}
sb.Append("</R>");
///pass XML string to DB side
///
//sb.ToString(); //here u get all data from data table as xml format
Database side Stored Procedure (you will need to update your table name):
CREATE PROCEDURE dbo.UpdateData
-- Add the parameters for the stored procedure here
@data XML
AS
BEGIN
SET NOCOUNT ON;
-- keep data into temp table
create table #tmp_data (id nchar(2),name varchar(20), number int)
DECLARE @XMLDocPointer INT
EXEC sp_xml_preparedocument @XMLDocPointer OUTPUT, @DATA
INSERT INTO #tmp_data(id,name,number)
SELECT ID,N,I
FROM OPENXML(@XMLDocPointer,'/R/C',2)
WITH(
ID nchar(30),
N VARCHAR(20),
I int
)
EXEC sp_xml_removedocument @XMLDocPointer
begin tran
-------------------INSERT not existing ones
INSERT INTO TABLE (id,name,number)
SELECT id,name,number
FROM #tmp_data
WHERE NOT EXISTS
(
SELECT 1
FROM TABLE
WHERE ID = #tmp_data.ID
)
--- update existing ones
UPDATE TABLE
SET name = #tmp_data.name, number = #tmp_data.number
FROM #tmp_data
WHERE #tmp_data.id = TABLE.id
commit tran
if(@@error <> 0)
rollback tran
END
来源:https://stackoverflow.com/questions/9222240/how-to-update-sql-server-table-with-data-from-other-source-datatable