更新(如果不存在)在SQL Server中使用XML输入参数插入

时间:2017-08-13 17:40:37

标签: sql-server xml xml-parsing

CREATE TABLE [dbo].[TelecommunicationsNumber]
(
    [ID] [int] NOT NULL,
    [ContactTypeID] [int] NOT NULL,
    [CountryID] [int] NOT NULL
)

以下是我对上述表格的XML输入示例。

DECLARE @TelecommunicationsNumberList XML = '<TelecommunicationsNumber><ContactTypeID>2</ContactTypeID><CountryID>1</CountryID></TelecommunicationsNumber><TelecommunicationsNumber><ContactTypeID>4</ContactTypeID><CountryID>1</CountryID></TelecommunicationsNumber>'

我想出了UPDATE SQL查询,如下所示。

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

如果输入XML和TelecommunicationsNumber表确实存在相同的ContactTypeID并且更新(如果存在),我如何插入新记录。

为了首先执行此操作,我必须获取行以检查天气是否存在ContactTypeID

问题:我无法弄清楚SELECT查询。如何通过编写SELECT查询来集成插入和更新查询。

我使用以下查询来插入记录。

  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)

1 个答案:

答案 0 :(得分:1)

我设法使用MERGE命令解决了这个问题。

;
  WITH TelecommunicationsNumber
  AS (SELECT
    ParamValues.x1.value('ContactTypeID[1]', 'int') AS ContactTypeID,
    ParamValues.x1.value('CountryID[1]', 'int') AS CountryID
  FROM @TelecommunicationsNumberList.nodes('/TelecommunicationsNumber') AS ParamValues (x1))
  MERGE INTO dbo.TelecommunicationsNumber AS old
  USING TelecommunicationsNumber AS new
  ON (new.ContactTypeID = old.ContactTypeID)
  WHEN MATCHED THEN UPDATE SET
  old.CountryID = new.CountryID
  WHEN NOT MATCHED THEN
  INSERT (ContactTypeID, CountryID)
  VALUES (new.ContactTypeID, new.CountryID);