I'm trying to update/insert data to postgresql depending whether given id is already preset in the table.
This works for update
UPDATE table SET
column=@Column
WHERE id=@Id;
And this works also (hardcoded values)
DO
$$
BEGIN
IF EXISTS (SELECT * FROM table WHERE id=123) THEN
UPDATE table SET
column=123
WHERE id=123;
ELSE
INSERT INTO table(id,column) VALUES (123,123);
END IF;
END
$$
But as soon as I try to give values as parameters, it breaks giving an error syntax error at or near "=@"
DO
$$
BEGIN
IF EXISTS (SELECT * FROM table WHERE id=@Id) THEN
UPDATE table SET
column=@Column
WHERE id=@Id;
ELSE
INSERT INTO table(id,column) VALUES (@Id,@Column);
END IF;
END
$$
To isolate the problem leaving just one parameter like this
DO
$$
BEGIN
IF EXISTS (SELECT * FROM table WHERE id=@Id) THEN
UPDATE table SET
column=123
WHERE id=123;
ELSE
INSERT INTO table(id,column) VALUES (123,123);
END IF;
END
$$
Gives error is Npgsql.PostgresException: '42703: column "id" does not exist'. So is there some kind of magic I have to do with the parameters?
Npgsql does not support parameters within dollar-quoted string literals ($$).
However, you seem to be implementing upsert (update or insert) - PostgreSQL supports that natively with INSERT ... ON CONFLICT
syntax. See this tutorial or other documentation on this feature, which should obviate the complexity of what you're trying to do.