Reputation: 1378
I have a table with unique constraint on 2 columns:
CREATE TABLE MIGRATION_DICTIONARIES.dbo._TableQueue_ (
Id INT IDENTITY PRIMARY KEY,
TableName VARCHAR(250),
TableFrom VARCHAR(250),
KeyName VARCHAR(250),
Processed INT DEFAULT 0,
CONSTRAINT [UQ_codes] UNIQUE NONCLUSTERED
(
TableName, TableFrom
)
)
In a procedure I am trying to implement I need to insert a bunch of records using INSERT INTO (...) SELECT. Now, how can I make sure that any rows that duplicate the constraint will be ignored but all the other rows given by the select statement still saved?
The query with insert:
INSERT INTO MIGRATION_DICTIONARIES.dbo._TableQueue_ (TableName, TableFrom, KeyName)
SELECT 'some_table_name', t.name as TableWithForeignKey, c.name as ForeignKeyColumn
from sys.foreign_key_columns as fk
inner join sys.tables as t on fk.parent_object_id = t.object_id
inner join sys.columns as c on fk.parent_object_id = c.object_id and fk.parent_column_id = c.column_id
where fk.referenced_object_id = (select object_id from sys.tables where name = 'some_table_name')
[EDIT] I ended with following query:
MERGE MIGRATION_DICTIONARIES.dbo._TableQueue_ AS T
USING (
SELECT 'SomeTable' as TableFrom, t.name as TableWithForeignKey, c.name as ForeignKeyColumn
from sys.foreign_key_columns as fk
inner join sys.tables as t on fk.parent_object_id = t.object_id
inner join sys.columns as c on fk.parent_object_id = c.object_id and fk.parent_column_id = c.column_id
where fk.referenced_object_id = (select object_id from sys.tables where name = 'SomeTable')
) AS S
ON (T.TableName = S.TableWithForeignKey AND T.TableFrom = S.TableFrom)
WHEN NOT MATCHED BY TARGET THEN
INSERT (TableName, TableFrom, KeyName)
VALUES (S.TableFrom, S.TableWithForeignKey, S.ForeignKeyColumn);
But when I run it I still get constraint error:
Violation of UNIQUE KEY constraint 'UQ_codes'. Cannot insert duplicate key in object 'dbo._TableQueue_'. The duplicate key value is (UP_Opiekun, UP_Uczen).
The statement has been terminated.
What do I do wrong?
Upvotes: 0
Views: 1410
Reputation: 432261
For SQL Server 2008 you can use the MERGE statement with only a "WHEN NOT MATCHED BY TARGET" clause to INSERT. Don't use a "WHEN MATCHED" clause
More generally, you can also use
INSERT dbo._TableQueue_
(....)
SELECT
...
FROM
SOurce S
WHERE
NOT EXISTS (SELECT *
FROM dbo._TableQueue_ T
WHERE
S.TableName = T.TableName AND S.TableFrom = T.TableFrom
)
After comment:
MERGE INTO dbo._TableQueue_ T
USING Source S
ON S.TableName = T.TableName AND S.TableFrom = T.TableFrom
WHEN NOT MATCHED BY TARGET THEN
INSERT (...)
VALUES (S.x. S.y, ...);
Upvotes: 2