What is a “INSERT IGNORE” equivalent in MS SQL Server?

后端 未结 2 1127
花落未央
花落未央 2021-01-01 13:26

I am trying to insert records into MySQL database from a MS SQL Server using the \"OPENQUERY\" but what I am trying to do is ignore the duplicate keys messages. so when the

相关标签:
2条回答
  • 2021-01-01 14:17

    If you are on SQL Server 2008+, you can use MERGE to do an INSERT if row does not exist, or an UPDATE.

    Example:

    MERGE
    INTO    dataValue dv
    USING   tmp_holding_DataValue t
    ON      t.dateStamp = dv.dateStamp
            AND t.itemId = dv.itemId
    WHEN NOT MATCHED THEN
    INSERT  (dateStamp, itemId, value)
    VALUES  (dateStamp, itemId, value)
    
    0 讨论(0)
  • 2021-01-01 14:27

    I don't think there is a specific option. But it is easy enough to do:

    insert into oldtable(. . .)
        select . . .
        from newtable
        where not exists (select 1 from oldtable where oldtable.id = newtable.id)
    

    If there is more than one set of unique keys, you can add additional not exists statements.

    EDIT:

    For the revised problem:

    insert into oldtable(. . .)
        select . . .
        from (select nt.*, row_number() over (partition by id order by (select null)) as seqnum
              from newtable nt
             ) nt
        where seqnum = 1 and
              not exists (select 1 from oldtable where oldtable.id = nt.id);
    

    The row_number() function assigns a sequential number to each row within a group of rows. The group is defined by the partition by statement. The numbers start at 1 and increment from there. The order by clause says that you don't care about the order. Exactly one row with each id will have a value of 1. Duplicate rows will have a value larger than one. The seqnum = 1 chooses exactly one row per id.

    0 讨论(0)
提交回复
热议问题