ADO.NET Provider for Microsoft Dynamics 365

Build 25.0.9434

UPSERT Statements

An UPSERT statement updates an existing record or creates a new record if an existing record is not identified.

UPSERT Syntax

The UPSERT syntax is the same as for INSERT. Microsoft Dynamics 365 uses the input provided in the VALUES clause to determine whether the record already exists. If the record does not exist, all columns required to insert the record must be specified. See Data Model for any table-specific information.

UPSERT INTO <table_name> 
( <column_reference> [ , ... ] )
VALUES 
( { <expression> | NULL } [ , ... ] ) 
  

<expression> ::=
  | @ <parameter> 
  | ?
  | <literal>

You can use the ExecuteNonQuery method to issue data manipulation commands and retrieve the rows affected, as shown in the following example:

C#

String connectionString = "InitiateOAuth=GETANDREFRESH;OrganizationUrl=https://myaccount.operations.dynamics.com/;Edition=Sales;";
int rowsAffected;
using (Dynamics365Connection connection = new Dynamics365Connection(connectionString)) {
  Dynamics365Command cmd = new Dynamics365Command("UPSERT INTO GoalHeadings (GoalHeadingId) VALUES ('John')", connection);
  rowsAffected = cmd.ExecuteNonQuery();
}

VB.NET

Dim connectionString As [String] = "InitiateOAuth=GETANDREFRESH;OrganizationUrl=https://myaccount.operations.dynamics.com/;Edition=Sales;"
Dim rowsAffected As [Integer]
Using connection As New Dynamics365Connection(connectionString)
  Dim cmd As New Dynamics365Command("UPSERT INTO GoalHeadings (GoalHeadingId) VALUES ('John')", connection)
  rowsAffected = cmd.ExecuteNonQuery()
End Using

Retrieving Generated Ids

To retrieve the GoalHeadingId of the last inserted record, use the SCOPE_IDENTITY function, as shown in the following example:

C#

  cmd = connection.CreateCommand();
  cmd.CommandText = "SELECT SCOPE_IDENTITY()";
  Object returnedValues = cmd.ExecuteScalar();
  String GoalHeadingId = (String)returnedValues;

  cmd = connection.CreateCommand()
  cmd.CommandText = "SELECT SCOPE_IDENTITY()"
  Dim returnedValues As [Object] = cmd.ExecuteScalar()
  Dim GoalHeadingId As [String] = returnedValues

Copyright (c) 2025 CData Software, Inc. - All rights reserved.
Build 25.0.9434