我每周都会收到一个 CSV 文件,我使用 BULK INSERT 将其导入我的 SQL 数据库。我插入一个临时表,然后通过插入新记录并更新任何已修改的记录将其与主表合并。代码是:
BULK INSERT dbo.temp
FROM 'C:\Users\Administrator\Documents\20120125.csv'
WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' );
MERGE dbo.main AS TargetTable
USING dbo.temp AS SourceTable
ON (TargetTable.name = SourceTable.name)
WHEN NOT MATCHED BY TARGET
THEN INSERT (name, age, gender, father, mother, teacher, mathsrating, historyrating, sciencerating, englishrating)
VALUES(SourceTable.name, SourceTable.age, SourceTable.gender, SourceTable.father, SourceTable.mother, SourceTable.teacher, SourceTable.mathsrating, SourceTable.historyrating, SourceTable.sciencerating, SourceTable.englishrating)
WHEN MATCHED
THEN UPDATE SET
TargetTable.name = SourceTable.name,
TargetTable.age = SourceTable.age,
TargetTable.gender = SourceTable.gender,
TargetTable.father = SourceTable.father,
TargetTable.mother = SourceTable.mother,
TargetTable.teacher = SourceTable.teacher,
TargetTable.mathsrating = SourceTable.mathsrating,
TargetTable.historyrating = SourceTable.historyrating,
TargetTable.sciencerating = SourceTable.sciencerating,
TargetTable.englishrating = SourceTable.englishrating;
DELETE FROM dbo.temp
我想要实现的是将被更新覆盖的记录及其“先前”值存储在一个新表中,以便我了解更改的历史。我对 SQL 相当陌生,但经过一些研究,似乎触发器可能是采用的方法,但欢迎任何有关如何解决此问题的建议。
谢谢
马特