MERGE Data-Set 1 Data-Set 2 BY Common Variable Following is the description of the parameters used −. Data-set1,Data-set2 are data set names written one after another. Common Variable is the variable based on whose matching values the data sets will be merged. Let us understand data merging with the help of an example. The merge function in BusinessObjects WebI makes it possible to create a report that displays query results from multiple data sets. You can merge: Queries on different universes (data sets) in the Data Warehouse; Multiple queries in the same universe; All of the queries must have at least one dimension object in common, for example, EmplID. The Pages Data Merge application is a powerful utility that transfers data and controls applications by using the built-in AppleScript scripting support of the iWork suite of applications. This application is a native OS X application written using AppleScriptObjective-C (ASOC), a dynamic fusion of the AppleScript and Objective-C languages. Every day, most analysts merge data in Excel and other spreadsheet programs to get better insights. Consolidating data in Excel is part of a bigger process called data preparation, but as the number of new data sources increases, merging data in spreadsheets is getting harder to do.
Permission level required | 2 |
---|---|
Restrictions | None |
The /data
command allows the user to get, merge, modify, and remove NBT data of a block entity, entity, or Command NBT storage.
Syntax[edit]
There are four instructions for /data
(get
, merge
, modify
, remove
), and the targets/sources referenced by each instruction command may be either block <targetPos>
, entity <target>
, or storage <target>
.
/data ...
... get
... (block <targetPos>|entity <target>|storage <target>) [<path>] [<scale>]
- Read off the entire NBT data or the subsection of the NBT data from the targeted block position or entity to the executor with syntax highlighting, scaled by <scale> if specified.
... merge
... (block <targetPos>|entity <target>|storage <target>) <nbt>
- Merge the NBT data from the sourced block position or entity with the specified
<nbt>
data.
- Merge the NBT data from the sourced block position or entity with the specified
... modify (block <targetPos>|entity <target>|storage <target>) <targetPath> ...
... append from (block <sourcePos>|entity <source>|storage <source>) [<sourcePath>]
... append value <value>
- Append the source data onto the end of the pointed-to list.
... insert <index> from (block <sourcePos>|entity <source>|storage <source>) [<sourcePath>]
... insert <index> value <value>
- Insert the source data into the pointed-to list as element
<index>
, then shift higher elements one position upwards.
- Insert the source data into the pointed-to list as element
... merge from (block <sourcePos>|entity <source>|storage <source>) [<sourcePath>]
... merge value <value>
- Merge the source data into the pointed-to object.
... prepend from (block <sourcePos>|entity <source>|storage <source>) [<sourcePath>]
... prepend value <value>
- Prepend the source data onto the beginning of the pointed-to list.
... set from (block <sourcePos>|entity <source>|storage <source>) [<sourcePath>]
... set value <value>
- Set the tag specified by
<targetPath>
to the source data.
- Set the tag specified by
... remove
... (block <targetPos>|entity <target>|storage <target>) <path>
- Removes NBT data at
<path>
from the targeted block position or entity. Player NBT data cannot be removed.
- Removes NBT data at
Syntax displayed in various ways
Arguments[edit]
<targetPos>
: block_pos
- The position of the target block entity whose NBT is to be operated on.
- It must be a block position composed of <x>, <y> and <z>, each of which must be an integer or tilde and caret notation.
<target>
: entity (in entity <target>
mode)
- Specifies an entity whose NBT is to be operated on.
- Must be a player name, a target selector or a UUID. And the target selector must be of single type.
<target>
: resource_location (in storage <target>
mode)
- Specifies a storage to be operated on.
- Must be a namespaced ID.
<path>
: nbt_path
- Specifies the NBT to retrieve or remove.
- Must be an NBT path.
<scale>
: double
- Scalar for the command's return value.
- Must be a Double-precision floating-point format number.
<nbt>
: nbt_compound_tag
- Specifies a compound tag to be merged into somewhere.
- Must be a Double-precision floating-point format number.
<targetPath>
: nbt_path
- Specifies target NBT to modify.
- Must be an NBT path.
<index>
: integer
- Specifies an item's index within a list.
- Must be a 32-bit integer number. And it must be between -2147483648 and 2147483647 (inclusive).
<sourcePos>
: block_pos
- The position of the target block entity whose NBT is to be used.
- It must be a block position composed of <x>, <y> and <z>, each of which must be an integer or tilde and caret notation.
<sourceEntity>
: entity
- Speciafies an entity whose NBT is to be used by
modify
. - Must be a player name, a target selector or a UUID. And the target selector must be of single type.
<sourceStorage>
: resource_location
- Specifies a storage to be used by
modify
. - Must be a namespaced ID.
<sourcePath>
: nbt_path
- Specifies the source NBT to be used by
modify
. - Must be an NBT path.
<value>
: nbt_tag
- Value used in modifying the target NBT. Should match its data type.
- Must be an NBT tag of any type in SNBT format.
Result[edit]
Command | Trigger | Java Edition |
---|---|---|
any | the arguments are not specified correctly | Unparseable |
<targetPos> is unloaded or out of the world | Failed | |
the block at <targetPos> is not a block entity | ||
<target> (in entity <target> mode) fails to resolve to an entity (named player must be online) | ||
/data get ... | more than one tag is got | |
/data get ... <path> | <path> does not exist | |
/data get ... <path> <scale> | the obtained tag is not a numeric tag | |
/data merge ... | nothing is changed | |
try to edit player's data | ||
/data remove ... | <path> is the root compound tag | |
/data modify ... from block ... | <sourcePos> is unloaded or out of the world | |
the block at <sourcePos> is not a block entity | ||
/data modify ... from entity ... | <sourceEntity> fails to resolve to an entity (named player must be online) | |
/data modify ... from ... <sourcePath> | <sourcePath> does not exist | |
/data modify ... append ... | the target tag isn't a list or array | |
source data isn't of an item type appropriate for the list | ||
/data modify ... insert <index> ... | the index is invalid | |
/data modify ... merge ... | the target path does not specify a compound tag | |
the source data is not a compound tag | ||
any | On success | Get, merge, modify, and remove NBT data. |
Output[edit]
Command | Edition | Situation | Success Count | /execute store success ... | /execute store result ... |
---|---|---|---|---|---|
any | Java Edition | On fail | 0 | 0 | 0 |
/data get ... | On success | 1 | 1 | 1 | |
/data get ... <path> | a numeric tag is got | 1 | 1 | the obtained value after rounding down[1] | |
a list or array tag is got | 1 | 1 | The number of elements in this list or array | ||
a string tag is got | 1 | 1 | The length of the string | ||
a compound tag is got | 1 | 1 | The number of tags that are direct children of that compound | ||
/data get ... <path> <scale> | On success | 1 | 1 | the obtained value multiplied by <scale> , then rounded down[2] | |
/data merge ... | On success | 1 | 1 | 1 | |
/data remove ... | On success | 1 | 1 | 1 | |
/data modify ... append ... | On success | 1 | 1 | the number of lists or arrays to which new elements are added | |
/data modify ... set ... | On success | 1 | 1 | the number of target tags that was successfully modified | |
/data modify ... merge ... | On success | 1 | 1 | the number of target compound tags that was successfully modified |
Examples[edit]
- To get the saturation level of the current player:
/data get entity @s foodSaturationLevel
- To make the nearest item within 10 blocks unable to be picked up by players:
/data modify entity @e[type=item,distance=..10,limit=1,sort=nearest] PickupDelay set value -1
- To get the Y-position of a random item:
/data get entity @e[type=item,limit=1,sort=random] Pos[1]
- To get the item ID of the item in the first hotbar slot of the nearest player:
/data get entity @p Inventory[{Slot:0b}].id
- To set the armor attribute of the dolphin closest to coordinates (0, 64, 0) to 20:
/data modify entity @e[x=0,y=64,z=0,type=dolphin,limit=1] Attributes[{Name:'generic.armor'}].Base set value 20
- To change the first item in a chest located at coordinates (1, 64, 1) into a diamond block, keeping all NBT data:
/data modify block 1 64 1 Items[0].id set value 'minecraft:diamond_block'
Storage[edit]
The command storage of NBT data is an efficient way for commands to access or save NBT data without an overhead for block entities or entities reading from or writing to the NBT data.
Each command storage is a general purpose, key-value storage, identified by a namespaced ID to prevent unintentional conflicts.
/data get
and /data modify
can read from the storage, while /data merge
, /data modify
, /data remove
, and /execute store
can write to the storage.
The command storage is accessible with JSON text as well.
History[edit]
Java Edition | |||||
---|---|---|---|---|---|
1.13 | 17w45b | Added /data . | |||
17w47a | Commands /blockdata and /entitydata have been removed as their features are merged into /data . | ||||
18w03a | Using /data get (block|entity|storage) with a path now works on non-numeric values. | ||||
1.14 | 18w43a | Added /data modify (block|entity|storage) . | |||
1.15 | 19w38a | Added command storage. | |||
Added storage <namespaced ID> as a source or target. | |||||
19w39a | Added NBT storage chat component. |
References[edit]
- ↑double n = (double)value;
int output = n < (int)n ? (int)n - 1 :(int)n; - ↑double n = (double)value * scale;
int output = n < (int)n ? (int)n - 1 :(int)n;
Applies to: SQL Server (all supported versions) Azure SQL Database Azure Synapse Analytics
Runs insert, update, or delete operations on a target table from the results of a join with a source table. For example, synchronize two tables by inserting, updating, or deleting rows in one table based on differences found in the other table.
Note
MERGE is currently in preview for Azure Synapse Analytics.
Performance Tip: The conditional behavior described for the MERGE statement works best when the two tables have a complex mixture of matching characteristics. For example, inserting a row if it doesn't exist, or updating a row if it matches. When simply updating one table based on the rows of another table, improve the performance and scalability with basic INSERT, UPDATE, and DELETE statements. For example:
Syntax
Note
To view Transact-SQL syntax for SQL Server 2014 and earlier, see Previous versions documentation.
Arguments
WITH <common_table_expression>
Specifies the temporary named result set or view, also known as common table expression, that's defined within the scope of the MERGE statement. The result set derives from a simple query and is referenced by the MERGE statement. For more information, see WITH common_table_expression (Transact-SQL).
TOP ( expression ) [ PERCENT ]
Specifies the number or percentage of affected rows. expression can be either a number or a percentage of the rows. The rows referenced in the TOP expression are not arranged in any order. For more information, see TOP (Transact-SQL).
The TOP clause applies after the entire source table and the entire target table join and the joined rows that don't qualify for an insert, update, or delete action are removed. The TOP clause further reduces the number of joined rows to the specified value. The insert, update, or delete actions apply to the remaining joined rows in an unordered way. That is, there's no order in which the rows are distributed among the actions defined in the WHEN clauses. For example, specifying TOP (10) affects 10 rows. Of these rows, 7 may be updated and 3 inserted, or 1 may be deleted, 5 updated, and 4 inserted, and so on.
Because the MERGE statement does a full table scan of both the source and target tables, I/O performance is sometimes affected when using the TOP clause to modify a large table by creating multiple batches. In this scenario, it's important to ensure that all successive batches target new rows.
database_name
The name of the database in which target_table is located.
schema_name
The name of the schema to which target_table belongs.
target_table
The table or view against which the data rows from <table_source> are matched based on <clause_search_condition>. target_table is the target of any insert, update, or delete operations specified by the WHEN clauses of the MERGE statement.
If target_table is a view, any actions against it must satisfy the conditions for updating views. For more information, see Modify Data Through a View.
target_table can't be a remote table. target_table can't have any rules defined on it.
[ AS ] table_alias
An alternative name to reference a table for the target_table.
USING <table_source>
Specifies the data source that's matched with the data rows in target_table based on <merge_search condition>. The result of this match dictates the actions to take by the WHEN clauses of the MERGE statement. <table_source> can be a remote table or a derived table that accesses remote tables.
<table_source> can be a derived table that uses the Transact-SQL table value constructor to construct a table by specifying multiple rows.
[ AS ] table_alias
An alternative name to reference a table for the table_source.
For more information about the syntax and arguments of this clause, see FROM (Transact-SQL).
ON <merge_search_condition>
Specifies the conditions on which <table_source> joins with target_table to determine where they match.
Pages Data Merge App
Caution
It's important to specify only the columns from the target table to use for matching purposes. That is, specify columns from the target table that are compared to the corresponding column of the source table. Don't attempt to improve query performance by filtering out rows in the target table in the ON clause; for example, such as specifying AND NOT target_table.column_x = value
. Doing so may return unexpected and incorrect results.
WHEN MATCHED THEN <merge_matched>
Specifies that all rows of *target_table, which match the rows returned by <table_source> ON <merge_search_condition>, and satisfy any additional search condition, are either updated or deleted according to the <merge_matched> clause.
The MERGE statement can have, at most, two WHEN MATCHED clauses. If two clauses are specified, the first clause must be accompanied by an AND <search_condition> clause. For any given row, the second WHEN MATCHED clause is only applied if the first isn't. If there are two WHEN MATCHED clauses, one must specify an UPDATE action and one must specify a DELETE action. When UPDATE is specified in the <merge_matched> clause, and more than one row of <table_source> matches a row in target_table based on <merge_search_condition>, SQL Server returns an error. The MERGE statement can't update the same row more than once, or update and delete the same row.
WHEN NOT MATCHED [ BY TARGET ] THEN <merge_not_matched>
Specifies that a row is inserted into target_table for every row returned by <table_source> ON <merge_search_condition> that doesn't match a row in target_table, but satisfies an additional search condition, if present. The values to insert are specified by the <merge_not_matched> clause. The MERGE statement can have only one WHEN NOT MATCHED [ BY TARGET ] clause.
WHEN NOT MATCHED BY SOURCE THEN <merge_matched>
Specifies that all rows of *target_table, which don't match the rows returned by <table_source> ON <merge_search_condition>, and that satisfy any additional search condition, are updated or deleted according to the <merge_matched> clause.
The MERGE statement can have at most two WHEN NOT MATCHED BY SOURCE clauses. If two clauses are specified, then the first clause must be accompanied by an AND <clause_search_condition> clause. For any given row, the second WHEN NOT MATCHED BY SOURCE clause is only applied if the first isn't. If there are two WHEN NOT MATCHED BY SOURCE clauses, then one must specify an UPDATE action and one must specify a DELETE action. Only columns from the target table can be referenced in <clause_search_condition>.
When no rows are returned by <table_source>, columns in the source table can't be accessed. If the update or delete action specified in the <merge_matched> clause references columns in the source table, error 207 (Invalid column name) is returned. For example, the clause WHEN NOT MATCHED BY SOURCE THEN UPDATE SET TargetTable.Col1 = SourceTable.Col1
may cause the statement to fail because Col1
in the source table is inaccessible.
Data Merge Minecraft
AND <clause_search_condition>
Specifies any valid search condition. For more information, see Search Condition (Transact-SQL).
<table_hint_limited>
Specifies one or more table hints to apply on the target table for each of the insert, update, or delete actions done by the MERGE statement. The WITH keyword and the parentheses are required.
NOLOCK and READUNCOMMITTED aren't allowed. For more information about table hints, see Table Hints (Transact-SQL).
Specifying the TABLOCK hint on a table that's the target of an INSERT statement has the same effect as specifying the TABLOCKX hint. An exclusive lock is taken on the table. When FORCESEEK is specified, it applies to the implicit instance of the target table joined with the source table.
Caution
Specifying READPAST with WHEN NOT MATCHED [ BY TARGET ] THEN INSERT may result in INSERT operations that violate UNIQUE constraints.
INDEX ( index_val [ ,...n ] )
Specifies the name or ID of one or more indexes on the target table for doing an implicit join with the source table. For more information, see Table Hints (Transact-SQL).
<output_clause>
Returns a row for every row in target_table that's updated, inserted, or deleted, in no particular order. $action can be specified in the output clause. $action is a column of type nvarchar(10) that returns one of three values for each row: 'INSERT', 'UPDATE', or 'DELETE', according to the action done on that row. For more information about the arguments and behavior of this clause, see OUTPUT Clause (Transact-SQL).
OPTION ( <query_hint> [ ,...n ] )
Specifies that optimizer hints are used to customize the way the Database Engine processes the statement. For more information, see Query Hints (Transact-SQL).
<merge_matched>
Specifies the update or delete action that's applied to all rows of target_table that don't match the rows returned by <table_source> ON <merge_search_condition>, and which satisfy any additional search condition.
UPDATE SET <set_clause>
Specifies the list of column or variable names to update in the target table and the values with which to update them.
For more information about the arguments of this clause, see UPDATE (Transact-SQL). Setting a variable to the same value as a column isn't supported.
DELETE
Specifies that the rows matching rows in target_table are deleted.
<merge_not_matched>
Specifies the values to insert into the target table.
(column_list)
A list of one or more columns of the target table in which to insert data. Columns must be specified as a single-part name or else the MERGE statement will fail. column_list must be enclosed in parentheses and delimited by commas.
VALUES ( values_list)
A comma-separated list of constants, variables, or expressions that return values to insert into the target table. Expressions can't contain an EXECUTE statement.
DEFAULT VALUES
Forces the inserted row to contain the default values defined for each column.
For more information about this clause, see INSERT (Transact-SQL).
<search_condition>
Specifies the search conditions to specify <merge_search_condition> or <clause_search_condition>. For more information about the arguments for this clause, see Search Condition (Transact-SQL).
<graph search pattern>
Specifies the graph match pattern. For more information about the arguments for this clause, see MATCH (Transact-SQL)
Remarks
Note
In Azure Synapse Analytics, the MERGE command (preview) has following differences compared to SQL server and Azure SQL database.
- A MERGE update is implemented as a delete and insert pair. The affected row count for a MERGE update includes the deleted and inserted rows.
- During the preview, MERGE…WHEN NOT MATCHED INSERT is not supported for tables with IDENTITY columns.
- The support for tables with different distribution types is described in this table:
MERGE CLAUSE in Azure Synapse Analytics | Supported TARGE distribution table | Supported SOURCE distribution table | Comment |
---|---|---|---|
WHEN MATCHED | All distribution types | All distribution types | |
NOT MATCHED BY TARGET | HASH | All distribution types | Use UPDATE/DELETE FROM…JOIN to synchronize two tables. |
NOT MATCHED BY SOURCE | All distribution types | All distribution types |
Important
Preview features are meant for testing only and should not be used on production instances or production data. Please also keep a copy of your test data if the data is important.
In Azure Synapse Analytics the MERGE command, currently in preview, may, under certain conditions, leave the target table in an inconsistent state, with rows placed in the wrong distribution, causing later queries to return wrong results in some cases. This problem may happen when these two conditions are met:
- The MERGE T-SQL statement was executed on a HASH distributed TARGET table in Azure Synapse SQL database AND
- The TARGET table of the merge has secondary indices or a UNIQUE constraint.
The problem has been fixed in Synapse SQL version 10.0.15563.0 and higher.
- To check, connect to the Synapse SQL database via SQL Server Management Studio (SSMS) and run
SELECT @@VERSION
. If the fix has not been applied, manually pause and resume your Synapse SQL pool to get the fix. - Until the fix has been verified applied to your Synapse SQL pool, avoid using the MERGE command on HASH distributed TARGET tables that have secondary indices or UNIQUE constraints.
- This fix doesn't repair tables already affected by the MERGE problem. Use scripts below to identify and repair any affected tables manually.
To check which hash distributed tables in a database cannot work with MERGE due to this issue, run this statement
To check if a hash distributed TARGET table for MERGE is affected by this issue, follow these steps to examine if the tables have rows landed in wrong distribution. If 'no need for repair' is returned, this table is not affected.
To repair affected tables, run these statements to copy all rows from the old table to a new table.
At least one of the three MATCHED clauses must be specified, but they can be specified in any order. A variable can't be updated more than once in the same MATCHED clause.
Any insert, update, or delete action specified on the target table by the MERGE statement are limited by any constraints defined on it, including any cascading referential integrity constraints. If IGNORE_DUP_KEY is ON for any unique indexes on the target table, MERGE ignores this setting.
The MERGE statement requires a semicolon (;) as a statement terminator. Error 10713 is raised when a MERGE statement is run without the terminator.
When used after MERGE, @@ROWCOUNT (Transact-SQL) returns the total number of rows inserted, updated, and deleted to the client.
MERGE is a fully reserved keyword when the database compatibility level is set to 100 or higher. The MERGE statement is available under both 90 and 100 database compatibility levels; however, the keyword isn't fully reserved when the database compatibility level is set to 90.
Don't use the MERGE statement when using queued updating replication. The MERGE and queued updating trigger aren't compatible. Replace the MERGE statement with an insert or an update statement.
Trigger implementation
For every insert, update, or delete action specified in the MERGE statement, SQL Server fires any corresponding AFTER triggers defined on the target table, but doesn't guarantee on which action to fire triggers first or last. Triggers defined for the same action honor the order you specify. For more information about setting trigger firing order, see Specify First and Last Triggers.
If the target table has an enabled INSTEAD OF trigger defined on it for an insert, update, or delete action done by a MERGE statement, it must have an enabled INSTEAD OF trigger for all of the actions specified in the MERGE statement.
If any INSTEAD OF UPDATE or INSTEAD OF DELETE triggers are defined on target_table, the update or delete operations aren't run. Instead, the triggers fire and the inserted and deleted tables then populate accordingly.
If any INSTEAD OF INSERT triggers are defined on target_table, the insert operation isn't performed. Instead, the table populates accordingly.
Permissions
Requires SELECT permission on the source table and INSERT, UPDATE, or DELETE permissions on the target table. For more information, see the Permissions section in the SELECT, INSERT, UPDATE, and DELETE articles.
Optimizing MERGE statement performance
By using the MERGE statement, you can replace the individual DML statements with a single statement. This can improve query performance because the operations are performed within a single statement, therefore, minimizing the number of times the data in the source and target tables are processed. However, performance gains depend on having correct indexes, joins, and other considerations in place.
Index best practices
To improve the performance of the MERGE statement, we recommend the following index guidelines:
- Create an index on the join columns in the source table that is unique and covering.
- Create a unique clustered index on the join columns in the target table.
These indexes ensure that the join keys are unique and the data in the tables is sorted. Query performance is improved because the query optimizer does not need to perform extra validation processing to locate and update duplicate rows and additional sort operations are not necessary.
JOIN best practices
To improve the performance of the MERGE statement and ensure correct results are obtained, we recommend the following join guidelines:
- Specify only search conditions in the ON <merge_search_condition> clause that determine the criteria for matching data in the source and target tables. That is, specify only columns from the target table that are compared to the corresponding columns of the source table.
- Do not include comparisons to other values such as a constant.
To filter out rows from the source or target tables, use one of the following methods.
- Specify the search condition for row filtering in the appropriate WHEN clause. For example, WHEN NOT MATCHED AND S.EmployeeName LIKE 'S%' THEN INSERT....
- Define a view on the source or target that returns the filtered rows and reference the view as the source or target table. If the view is defined on the target table, any actions against it must satisfy the conditions for updating views. For more information about updating data by using a view, see Modifying Data Through a View.
- Use the
WITH <common table expression>
clause to filter out rows from the source or target tables. This method is similar to specifying additional search criteria in the ON clause and may produce incorrect results. We recommend that you avoid using this method or test thoroughly before implementing it.
The join operation in the MERGE statement is optimized in the same way as a join in a SELECT statement. That is, when SQL Server processes joins, the query optimizer chooses the most efficient method (out of several possibilities) of processing the join. When the source and target are of similar size and the index guidelines described previously are applied to the source and target tables, a merge join operator is the most efficient query plan. This is because both tables are scanned once and there is no need to sort the data. When the source is smaller than the target table, a nested loops operator is preferable.
You can force the use of a specific join by specifying the OPTION (<query_hint>)
clause in the MERGE statement. We recommend that you do not use the hash join as a query hint for MERGE statements because this join type does not use indexes.
Parameterization best practices
If a SELECT, INSERT, UPDATE, or DELETE statement is executed without parameters, the SQL Server query optimizer may choose to parameterize the statement internally. This means that any literal values that are contained in the query are substituted with parameters. For example, the statement INSERT dbo.MyTable (Col1, Col2) VALUES (1, 10), may be implemented internally as INSERT dbo.MyTable (Col1, Col2) VALUES (@p1, @p2). This process, called simple parameterization, increases the ability of the relational engine to match new SQL statements with existing, previously-compiled execution plans. Query performance may be improved because the frequency of query compilations and recompilations are reduced. The query optimizer does not apply the simple parameterization process to MERGE statements. Therefore, MERGE statements that contain literal values may not perform as well as individual INSERT, UPDATE, or DELETE statements because a new plan is compiled each time the MERGE statement is executed.
To improve query performance, we recommend the following parameterization guidelines:
- Parameterize all literal values in the
ON <merge_search_condition>
clause and in the theWHEN
clauses of the MERGE statement. For example, you can incorporate the MERGE statement into a stored procedure replacing the literal values with appropriate input parameters. - If you cannot parameterize the statement, create a plan guide of type
TEMPLATE
and specify thePARAMETERIZATION FORCED
query hint in the plan guide. - If MERGE statements are executed frequently on the database, consider setting the PARAMETERIZATION option on the database to FORCED. Use caution when setting this option. The
PARAMETERIZATION
option is a database-level setting and affects how all queries against the database are processed.
TOP Clause best practices
In the MERGE statement, the TOP clause specifies the number or percentage of rows that are affected after the source table and the target table are joined, and after rows that do not qualify for an insert, update, or delete action are removed. The TOP clause further reduces the number of joined rows to the specified value and the insert, update, or delete actions are applied to the remaining joined rows in an unordered fashion. That is, there is no order in which the rows are distributed among the actions defined in the WHEN clauses. For example, specifying TOP (10) affects 10 rows; of these rows, 7 may be updated and 3 inserted, or 1 may be deleted, 5 updated, and 4 inserted and so on.
It is common to use the TOP clause to perform data manipulation language (DML) operations on a large table in batches. When using the TOP clause in the MERGE statement for this purpose, it is important to understand the following implications.
I/O performance may be affected.
The MERGE statement performs a full table scan of both the source and target tables. Dividing the operation into batches reduces the number of write operations performed per batch; however, each batch will perform a full table scan of the source and target tables. The resulting read activity may affect the performance of the query.
Incorrect results can occur.
It is important to ensure that all successive batches target new rows or undesired behavior such as incorrectly inserting duplicate rows into the target table can occur. This can happen when the source table includes a row that was not in a target batch but was in the overall target table.
To insure correct results:
- Use the ON clause to determine which source rows affect existing target rows and which are genuinely new.
- Use an additional condition in the WHEN MATCHED clause to determine if the target row has already been updated by a previous batch.
Because the TOP clause is only applied after these clauses are applied, each execution either inserts one genuinely unmatched row or updates one existing row.
Bulk Load best practices
The MERGE statement can be used to efficiently bulk load data from a source data file into a target table by specifying the OPENROWSET(BULK…)
clause as the table source. By doing so, the entire file is processed in a single batch.
To improve the performance of the bulk merge process, we recommend the following guidelines:
Create a clustered index on the join columns in the target table.
Use the ORDER and UNIQUE hints in the
OPENROWSET(BULK…)
clause to specify how the source data file is sorted.By default, the bulk operation assumes the data file is unordered. Therefore, it is important that the source data is sorted according to the clustered index on the target table and that the ORDER hint is used to indicate the order so that the query optimizer can generate a more efficient query plan. Hints are validated at runtime; if the data stream does not conform to the specified hints, an error is raised.
These guidelines ensure that the join keys are unique and the sort order of the data in the source file matches the target table. Query performance is improved because additional sort operations are not necessary and unnecessary data copies are not required.
Measuring and diagnosing MERGE performance
The following features are available to assist you in measuring and diagnosing the performance of MERGE statements.
- Use the merge stmt counter in the sys.dm_exec_query_optimizer_info dynamic management view to return the number of query optimizations that are for MERGE statements.
- Use the merge_action_type attribute in the sys.dm_exec_plan_attributes dynamic management view to return the type of trigger execution plan used as the result of a MERGE statement.
- Use SQL Trace to gather troubleshooting data for the MERGE statement in the same way you would for other data manipulation language (DML) statements. For more information, see SQL Trace.
Examples
A. Using MERGE to do INSERT and UPDATE operations on a table in a single statement
A common scenario is updating one or more columns in a table if a matching row exists. Or, inserting the data as a new row if a matching row doesn't exist. You usually do either scenario by passing parameters to a stored procedure that contains the appropriate UPDATE and INSERT statements. With the MERGE statement, you can do both tasks in a single statement. The following example shows a stored procedure in the AdventureWorks2012database that contains both an INSERT statement and an UPDATE statement. The procedure is then modified to run the equivalent operations by using a single MERGE statement.
B. Using MERGE to do UPDATE and DELETE operations on a table in a single statement
The following example uses MERGE to update the ProductInventory
table in the AdventureWorks2012 sample database, daily, based on orders that are processed in the SalesOrderDetail
table. The Quantity
column of the ProductInventory
table is updated by subtracting the number of orders placed each day for each product in the SalesOrderDetail
table. If the number of orders for a product drops the inventory level of a product to 0 or less, the row for that product is deleted from the ProductInventory
table.
C. Using MERGE to do UPDATE and INSERT operations on a target table by using a derived source table
The following example uses MERGE to modify the SalesReason
table in the AdventureWorks2012 database by either updating or inserting rows. When the value of NewName
in the source table matches a value in the Name
column of the target table, (SalesReason
), the ReasonType
column is updated in the target table. When the value of NewName
doesn't match, the source row is inserted into the target table. The source table is a derived table that uses the Transact-SQL table value constructor to specify multiple rows for the source table. For more information about using the table value constructor in a derived table, see Table Value Constructor (Transact-SQL). The example also shows how to store the results of the OUTPUT clause in a table variable. And, then you summarize the results of the MERGE statement by running a simple select operation that returns the count of inserted and updated rows.
D. Inserting the results of the MERGE statement into another table
The following example captures data returned from the OUTPUT clause of a MERGE statement and inserts that data into another table. The MERGE statement updates the Quantity
column of the ProductInventory
table in the AdventureWorks2012 database, based on orders that are processed in the SalesOrderDetail
table. The example captures the updated rows and inserts them into another table that's used to track inventory changes.
E. Using MERGE to do INSERT or UPDATE on a target edge table in a graph database
In this example, you create node tables Person
and City
and an edge table livesIn
. You use the MERGE statement on the livesIn
edge and insert a new row if the edge doesn't already exist between a Person
and City
. If the edge already exists, then you just update the StreetAddress attribute on the livesIn
edge.