2017-08-13 7 views
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) 
+2

あなたが指定することができます[ 'merge'](https://docs.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql)を見てください行が存在する場合は 'update'、行頭がない場合は' insert'を返します。 – Andomar

+0

@Andomarコメントをいただきありがとうございます。私は 'merge'コマンドを使って私の問題を解決することができました。今はうまく動作します。 –

答えて

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); 
関連する問題