【发布时间】: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