1
CREATE TABLE [dbo].[TelecommunicationsNumber]
(
[ID] [int] NOT NULL,
[ContactTypeID] [int] NOT NULL,
[CountryID] [int] NOT NULL
)
上記の表へのサンプルXML入力です。更新(存在しない場合)SQLサーバーでXML入力パラメータを使用して挿入
DECLARE @TelecommunicationsNumberList XML = '<TelecommunicationsNumber><ContactTypeID>2</ContactTypeID><CountryID>1</CountryID></TelecommunicationsNumber><TelecommunicationsNumber><ContactTypeID>4</ContactTypeID><CountryID>1</CountryID></TelecommunicationsNumber>'
私は以下のようにUPDATE SQLクエリを見つけました。存在する場合、私は、入力XMLとTelecommunicationsNumber
表がない場合は、新しいレコードを挿入するにはどうすればよい
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
は同じ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)
あなたが指定することができます[ 'merge'](https://docs.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql)を見てください行が存在する場合は 'update'、行頭がない場合は' insert'を返します。 – Andomar
@Andomarコメントをいただきありがとうございます。私は 'merge'コマンドを使って私の問題を解決することができました。今はうまく動作します。 –