如何避免数据重复插入?

How to avoid data repetition insertion?

最近我发布了一个,它包含一些语法错误,现在代码是运行没有错误,感谢@Arulkumar。

但现在我又面临一个问题,来自 excel sheet 的数据正确存储在 SQL 服务器数据库中,但是当我按下刷新按钮或者如果我去link 再次在我的应用程序中,数据在数据库中重复。再次意味着它正在从 excel 中检索值并将相同的数据再次存储在数据库中。

如何避免数据重复。谁能帮我解决这个问题?上面提到的 link 中有代码和 excel sheet 示例。

您需要 MERGE 语句

request.query('MERGE [mytable] as target USING (SELECT SalesPersonID, TerritoryID FROM OPENROWSET('  + 
        '\'Microsoft.ACE.OLEDB.12.0\', \'Excel 12.0;Database=D:\sample\test\data\1540_OPENROWSET_Examples.xls;HDR=YES\', ' + 
        '\'SELECT SalesPersonID, TerritoryID FROM [SELECT_Example$]\')' +
        ' ) as source' +
        ' ON target.SalesPersonID = source.SalesPersonID' +
        ' WHEN MATCHED THEN UPDATE SET TerritoryID = source.TerritoryID' +
        ' WHEN NOT MATCHED THEN INSERT (SalesPersonID, TerritoryID) VALUES (source.SalesPersonID, source.TerritoryID);'
        ,function(err,recordset){
    if(err) console.log(err)

如果已经有具有相同 SalesPersonID 的行,它将更新 TerritoryID,如果 mytable 中没有匹配项,则插入行。

如果您需要在两个字段上加入,请更改:

ON target.SalesPersonID = source.SalesPersonID

关于这个:

ON target.SalesPersonID = source.SalesPersonID AND target.TerritoryID = source.TerritoryID

之后 - 删除此字符串,因为它不再需要了:

'WHEN MATCHED THEN UPDATE SET TerritoryID = source.TerritoryID' +