sqlserver icon indicating copy to clipboard operation
sqlserver copied to clipboard

MERGE queries shouldn't require primary key setting.

Open sblackstone opened this issue 1 year ago • 4 comments

Describe the feature

Merge (upsert) queries currently require all of the columns in clause.Conflict.Columns to be primary keys, otherwise it silently falls back to a regular insert.

A table can have a primary key thats simply an auto-increment referencing the row, but also unique constraints which can trigger the ON CONFLICT case of a merge query.

Motivation

Upsert queries that aren't necessarily looking at the primary key.


	MERGE table1 AS [Target] USING (
	SELECT
	uniq_field1 = ?,
	uniq_field2   = ?,
	value = ?)
	AS [Source] ON [Target].uniq_field1 = [Source].uniq_field1 and [Target].uniq_field2 = [Source].uniq_field2
	WHEN MATCHED THEN
	UPDATE
		SET
		[Target].value=[Source].value,
		WHEN NOT MATCHED THEN
		INSERT (
			uniq_field1,
			uniq_field2,
			value)
	VALUES
		(
			[Source].uniq_field1,
			[Source].uniq_field2,
			[Source].value
		)

Related Issues

None.

sblackstone avatar May 31 '23 14:05 sblackstone

Additionally, the fall-back behavior when an on-conflict clause exists but doesn't match the primary keys was super-confusing and I'd suggest that it should return an error rather than just doing an insert.

sblackstone avatar May 31 '23 14:05 sblackstone

Any good news on this issue?

jhajjaarap avatar Dec 08 '23 08:12 jhajjaarap

Would be nice to have @jhajjaarap's patch upstreamed! :tada:

sblackstone avatar Jan 09 '24 19:01 sblackstone

@jhajjaarap Perhaps create a pull request for upstreaming your fix? Would love to get that merged.

muety avatar Jan 16 '24 17:01 muety