CREATE TABLE [dbo].[TelecommunicationsNumber]
(
[ID] [int] NOT NULL,
[ContactTypeID] [int] NOT NULL,
[CountryID] [int] NOT NULL
)
Here is my sample XML input to the above mentioned table.
DECLARE @TelecommunicationsNumberList XML = '<TelecommunicationsNumber><ContactTypeID>2</ContactTypeID><CountryID>1</CountryID></TelecommunicationsNumber><TelecommunicationsNumber><ContactTypeID>4</ContactTypeID><CountryID>1</CountryID></TelecommunicationsNumber>'
I figured out the UPDATE SQL query as below.
UPDATE TelecommunicationsNumber
SET ContactTypeID = n.ContactTypeID,
CountryID = n.CountryID
FROM (SELECT
T.C.value('(ContactTypeID)[1]', 'INT') AS ContactTypeID,
T.C.value('(CountryID)[1]', 'INT') AS CountryID
FROM
@TelecommunicationsNumberList.nodes('/TelecommunicationsNumber') AS T (C)) AS n
WHERE
TelecommunicationsNumber.ContactTypeID = n.ContactTypeID
How can I insert a new record if the input XML and the TelecommunicationsNumber table does exists the same ContactTypeID and update if exists.
In order to do that first I have to fetch the rows in order to check weather the same ContactTypeID exists or not.
QUESTION: I am unable to figure out the SELECT query. How can I integrate both the insert and update queries by writing the SELECT query.
I use the below query to INSERT the records.
INSERT INTO TelecommunicationsNumber (ContactTypeID,CountryID)
SELECT
Entries.value('(ContactTypeID)[1]', 'INT') AS 'ContactTypeID',
Entries.value('(CountryID)[1]', 'nvarchar(256)') AS 'CountryID'
FROM
@TelecommunicationsNumberList.nodes('/TelecommunicationsNumber') AS TelecommunicationsNumberEntries (Entries)
mergewhich allows you to specify anupdatewhen a row exists, and aninsertwhen it does notmergecommand. Now its working fine.