I have a couple of queries that I'm trying to combine together into a function that returns some values back. Except I can't figure out how to do it correctly.
This is the logic im trying to output:
if((SELECT parent_id FROM event_comments WHERE comment_id = $1) == null){
WITH cte AS (DELETE FROM event_comments WHERE thread_id = '1BZbAR'
RETURNING parent_id, comment_id, thread_id)
SELECT parent_id, comment_id, thread_id
FROM cte
WHERE parent_id IS NULL;
}else{
DELETE FROM event_comments WHERE comment_id = $1 AND created_by = $3
returning parent_id, comment_id, thread_id
}
Getting the syntax error type "cte" does not exist?
CREATE FUNCTION deleteComment(comment_id integer, created_by UUID, thread_id integer)
RETURNS cte AS $$
BEGIN
CASE WHEN (SELECT parent_id FROM event_comments WHERE comment_id = $1) is NULL
THEN
WITH cte AS (
DELETE FROM event_comments WHERE thread_id = $3
RETURNING parent_id, comment_id, thread_id
)
SELECT parent_id, comment_id, thread_id
FROM cte
WHERE parent_id IS NULL;
ELSE
WITH cte AS (
DELETE FROM event_comments WHERE comment_id = $1 AND created_by = $2
returning parent_id, comment_id, thread_id
)
END; $$
LANGUAGE plpgsql;