I'm new to MERGE and an index novice so bear with me...
I have a stored procedure that builds a #changes
temp table, UPDATEs a prod_tbl
table based on #changes
, then INSERTs the before and after values into auto_update_log
table that is quickly growing with duplicate rows. In order to prevent this, I'd like to use the MERGE statement. Speed is paramount, as well as thread safety, because this table will be manipulated throughout the day.
There aren't any existing indexes on auto_update_log
, nor is there any type of key. My idea is to create a multi-column index using a key column (from the auto_update_log
table) and all of the before and after columns to help speed things up with the MERGE. There are going to be 6 before and after columns plus the one key column that relates back to the PK of auto_update_log
.
Sample Log Table:
CREATE TABLE dbo.sample_auto_update_log (
id INT NOT NULL, --Primary key from [prod_tbl]
item_a_before VARCHAR(25) NULL, --[prod_tbl].[item_a]
item_a_detail VARCHAR(25) NULL, --Value from elsewhere in the DB that applies
item_a_after VARCHAR(25) NULL, --The new value SET for [prod_tbl].[item_a]
update_count INT NOT NULL DEFAULT (0),
update_datetime DATETIME NOT NULL DEFAULT (GETDATE())
);
Sample MERGE:
MERGE sample_auto_update_log WITH (HOLDLOCK) AS t
USING #changes AS s
ON (t.id = s.id AND t.item_a_before = s.item_a_before AND t.item_a_after = s.item_a_after)
WHEN MATCHED THEN
UPDATE
SET update_count = update_count + 1, update_datetime = GETDATE()
WHEN NOT MATCHED THEN
INSERT (id, item_a_before, item_a_detail, item_a_after)
VALUES (s.id, s.item_a_before, s.item_a_detail, s.item_a_after);
Question: How can i best optimize the MERGE using indexes or other methods?