I have an XML data source stored in a Temporary Table using XQuery, and have successfully inserted this into the database.
My problem is that I don't know how to check if something exists first, and then delete it, base on the statement. Here's the insertion code:
SELECT
N.value('id-number[1]', 'VARCHAR(10)') as IdNumber,
N.value('irrelevant1[1]', 'VARCHAR(12)') as Irrelevant1,
N.value('irrelevant2[1]', 'VARCHAR(14)') as Irrelevant2,
N.value('irrelevant3[1]', 'VARCHAR(16)') as Irrelevant3,
N.value('irrelevant4[1]', 'VARCHAR(18)') as Irrelevant4,
N.value('irrelevant5[1]', 'VARCHAR(20)') as Irrelevant5,
INTO #TempTable
FROM @xml.nodes('nodes/here') AS X(N)
INSERT INTO [main-entry] SELECT * FROM #TempTable
Now, what I want to do, before insertion, is to find out whether or not this record, based on id-number
, exists in the database. If it exists, then delete it. It has a CASCADE DELETE
option on the child records, so those should also be deleted along with the main entry record.
Here's what I'm using:
IF (SELECT IdNumber FROM #TempTable) IN (SELECT [id-number] FROM [main-entry])
BEGIN
DELETE FROM [main-entry] WHERE [id-number] = ''
END
This obviously won't work since both are selecting a large amount of id-numbers.
How do I do this?
- If id-number exists in both the main table, and in the #TempTable,
DELETE
it. - If it does not exist in both,
INSERT
records. (insert code is finished)
I do have a unique index on id-number, so it will not allow me to insert anything else if that number already exists. So, I figured the best way to handle this is to delete said record.
I've tried a MERGE
statement, but I can't add INSERT
code to WHEN MATCHED THEN
, so I would have to run the query twice to insert. WHEN MATCHED THEN DELETE
DOES work, but it doesn't allow me to insert additional records.