【问题标题】:How to avoid data repetition insertion?如何避免数据重复插入?
【发布时间】:2016-05-11 06:35:11
【问题描述】:

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

但现在我又面临一个问题,Excel 表中的数据正确存储到 SQL Server 数据库中,但是当我按下刷新按钮或在我的应用程序中再次转到该链接时,数据在数据库中重复出现。再次意味着它正在从 excel 中检索值并将相同的数据再次存储在数据库中。

如何避免数据重复。有人可以帮我解决这个问题吗?代码和 Excel 表示例在上述链接中。

【问题讨论】:

    标签: sql-server node.js excel openrowset node-mssql


    【解决方案1】:

    你需要 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' + 
    

    【讨论】:

    • 嗨,感谢您逐行解释,我尝试运行代码,它给出了一些语法错误:
    • { [RequestError: Incorrect syntax near the keyword 'as'.] name: 'RequestError', message: 'Incorrect syntax near the keyword \'as\'.', code: 'EREQUEST', number: 156, lineNumber: 1, class: 15, serverName: 'localhost\\SQLEXPRESS', procName: '', precedingErrors: [ { [RequestError: Incorrect syntax near '('.] name: 'RequestError', message: 'Incorrect syntax near \'(\'.', code: 'EREQUEST', number: 102, lineNumber: 1, state: 1, class: 15, serverName: 'localhost\\SQLEXPRESS', procName: '' } ] }
    • 等一下,我搞砸了代码格式!
    • 感谢您的回复。我尝试运行更新的代码,现在不存在语法错误,但它显示此消息:RequestError: A MERGE statement must be terminate by a semi-colon (;).]
    • 只需在查询末尾添加;(我添加这个来回答)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多