Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mssql(sql server):batch upsert error... (upsert multiple rows) #828

Closed
chouqimin opened this issue Aug 4, 2022 · 2 comments
Closed

mssql(sql server):batch upsert error... (upsert multiple rows) #828

chouqimin opened this issue Aug 4, 2022 · 2 comments

Comments

@chouqimin
Copy link

chouqimin commented Aug 4, 2022

when I use sql server batch insert and update

CREATE TABLE test_table(keycol CHAR(1) PRIMARY KEY, col1 CHAR(1), col2 CHAR(1));
data := []map[string]interface{}{
		{"keycol": "A", "col1": "1", "col2": "1"},
		{"keycol": "B", "col1": "2", "col2": "2"},
		{"keycol": "C", "col1": "3", "col2": "3"},
		{"keycol": "D", "col1": "4", "col2": "4"},
	}

sql_upsert := `
		MERGE test_table trg
		USING (VALUES (:keycol, :col1, :col2)) src(keycol, col1, col2)
			ON trg.keycol = src.keycol
		WHEN MATCHED THEN
			UPDATE SET col1 = src.col1, col2 = src.col2
		WHEN NOT MATCHED THEN
			INSERT(keycol, col1, col2)
			VALUES(src.keycol, src.col1, src.col2);
		`

_, err := tx.NamedExec(sql_upsert, data)

I got error sql: expected 3 arguments, got 12

when len(data) = 1 is no problem

I want to confirm whether the batch insert of sql server is not yet supported?

@rosehsu47
Copy link

rosehsu47 commented Aug 4, 2022

same question here 🙏

@chouqimin chouqimin changed the title sql server upsert multiple rows error mssql(sql server):batch upsert error... (upsert multiple rows) Aug 14, 2022
@chouqimin
Copy link
Author

I temporarily solve my problem according to issue 796
Because the regex of sqlx v1.3.5 requires a closing bracket before values
So I added a line of comment --) to my query to temporarily solve my problem

MERGE test_table trg
USING (VALUES (:keycol, :col1, :col2)) src(keycol, col1, col2)
	ON trg.keycol = src.keycol
WHEN MATCHED THEN
	UPDATE SET col1 = src.col1, col2 = src.col2
WHEN NOT MATCHED THEN
	INSERT(keycol, col1, col2)
	VALUES(src.keycol, src.col1, src.col2);

To

MERGE test_table trg
USING (
-- )
VALUES (:keycol, :col1, :col2)) src(keycol, col1, col2)
	ON trg.keycol = src.keycol
WHEN MATCHED THEN
	UPDATE SET col1 = src.col1, col2 = src.col2
WHEN NOT MATCHED THEN
	INSERT(keycol, col1, col2)
	VALUES(src.keycol, src.col1, src.col2);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants