【问题标题】:Update, if not exists Insert using XML input parameter in SQL Server更新(如果不存在) 在 SQL Server 中使用 XML 输入参数插入
【发布时间】:2017-08-13 17:40:37
【问题描述】:
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

QUESTION:我无法弄清楚 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)

【问题讨论】:

  • 查看merge,它允许您在存在行时指定update,在不存在时指定insert
  • @Andomar 感谢您的评论。我能够使用merge 命令解决我的问题。现在它工作正常。

标签: sql-server xml xml-parsing


【解决方案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);

【讨论】:

    猜你喜欢
    • 2014-01-25
    • 1970-01-01
    • 2012-08-08
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多