Sometimes you need to update a table from the rows in a CSV
file. MS SQL offers BULK INSERT FROM
and MERGE
as a way to achieve this.
BULK INSERT
mySourceTable
FROM
'/path/to/data.csv'
WITH (
FIELDTERMINATOR = ','
,ROWTERMINATOR = '\n'
,FIRSTROW = 2
);
MERGE
myTargetTable AS TargetTable
USING
mySourceTable AS SourceTable
ON (
TargetTable.keyField = SourceTable.keyField
)
WHEN MATCHED THEN
UPDATE SET
TargetTable.column1 = SourceTable.column1,
TargetTable.column2 = SourceTable.column2
WHEN NOT MATCHED BY TARGET THEN
INSERT (
column1, column2
) VALUES (
SourceTable.column1, SourceTable.column2
);