1

I'm looking for a way to have a function or procedure in Postgresql 12, which can be called with a single line for usage in commandline.

1) Perform a query that takes a parameter as input

For example:
select id from table1 where name = $PARAMETER

2) Based on the ids returned, execute multiple deletes

For example:

delete from table2 where id = $id
delete from table3 where id = $id

In SQL Server I would use a stored procedure for this, but I'm lost on how how to do this in PostgreSQL.

3
  • Postgres also has the concept of stored procedures and functions. If you can write them in SQL Server you shouldn't have much problem adapting to the plpgsql syntax. Commented May 15, 2020 at 17:26
  • @steiner: that is completely incorrect. That's completely different compared to sql server. Commented May 15, 2020 at 18:09
  • I'm not saying the syntax is exactly the same. I'm saying with some research and reading you should be able to adapt it. Commented May 18, 2020 at 19:37

1 Answer 1

1

If your origin is on MS SQL, then good start is reading documentation. The language and environment is different (maybe very different to what you know).

But your task is simple - you can use procedures (from Postgres 11) or functions:

CREATE OR REPLACE FUNCTION s(_name text)
RETURNS void AS $$
DECLARE _id int;
BEGIN
  SELECT id FROM table1 WHERE name = _name INTO _id;
  DELETE FROM table2 WHERE id = _id;
  DELETE FROM table2 WHERE id = _id;
END
$$ LANGUAGE plpgsql;

or like procedure

CREATE OR REPLACE PROCEDURE s(_name text)
AS $$
DECLARE _id int;
BEGIN
  SELECT id FROM table1 WHERE name = _name INTO _id;
  DELETE FROM table2 WHERE id = _id;
  DELETE FROM table2 WHERE id = _id;
END
$$ LANGUAGE plpgsql;

Function is executed via SELECT s('somename')

Procedure is executed by statement CALL s('somename')

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.