Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL Server ignore_dup_key on apparently ignored for merge statement
    primarykey
    data
    text
    <p>SQL Server 2008.</p> <p>I have few pieces of code working together and the effect is rather strange so I decided to share.</p> <p>I have a table with emails - for simplicity let as assume there are 2 columns: ID identity(1,1) int primary key email varchar(900)</p> <p>Also there is a unique key on email column with IGNORE_DUP_KEY = ON.</p> <p>On the other side of a problem is a merge statement:</p> <pre><code>merge into dbo.email using ( select distinct email t from #t ) p ON t = email when not matched by target then insert (email) values (t); </code></pre> <p>It is worth to note that #t is basically (for purpose of this query) a one column table with email varchar(500).</p> <p>What is surprising is that the query failed:</p> <p>"Violation of UNIQUE KEY constraint 'uq_email'. Cannot insert duplicate key in object dbo.email"</p> <p>However this works flawlessly:</p> <pre><code>insert into dbo.email (email) select email from #t </code></pre> <p>While I can obviously work around the problem (the insert statement is faster anyway so it is a way to go) I have no idea why the MERGE statement failed. Any ideas, anyone?</p> <p>EDIT: Full use case: Step 1:</p> <pre><code>create table #temp ( col1 varchar(500), col2 varchar(500), col3 varchar(500), col4 varchar(500), col5 varchar(500), email varchar(500), id int) </code></pre> <p>Step 2:</p> <p>#temp is populated from CSV file for many purposes</p> <p>Step 3:</p> <p>merge into dbo.email using ( select distinct email t from #temp ) p ON t = email when not matched by target then insert (email) values (t);</p> <p>Step 0 - CREATE script for dbo.email:</p> <pre><code>CREATE TABLE dbo.email ( id int identity(1,1) not null, email varchar(900) null, loaddate date default null, constraint [PK__email__1111] PRIMARY KEY CLUSTERED ( id asc ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON PRIMARY, CONSTRAINT [uq_email] UNIQUE NONCLUSTERED ( EMAIL asc ) ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = ON, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON PRIMARY ) ON PRIMARY </code></pre> <p>I can't make much more without giving you hunderds of gigabytes of data which is out of a question obviously.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload