Variables in conditional query

Goal: We want to pass current_user.id (or any other dynamic value) in a condition query.

Steps: -->

DO $$

DECLARE v_USERID INT := {{ current_user.id }};
DECLARE v_Message VARCHAR(100);

BEGIN
    -- Conditional logic
    IF v_USERID > 0 THEN
        v_Message := 'User id found;
    ELSE
        v_Message := 'User id not found';
    END IF;

    RAISE NOTICE '%', v_Message;

END $$;

It gives following error:
bind message supplies 1 parameters, but prepared statement "" requires 0

But if pass it in a simple query like following, it works fine.

SELECT * from TABLE_NAME where user_id = {{ current_user.id }};

hey @JawadAzizFarhad and welcome!

personally i pre-compute my database query strings in javascript because the syntax highlighting in retool gets the colors all wrong when you place a variable inside single quotes (eg. mycolumn = '{{my_query.value}}')

so try that out and see if you still get the error, and if so you also have this option:

Resources > your resource > "Advanced options" at the bottom of the page > "Disable converting queries to prepared statements" checkbox

try those two things out and let me know, good luck!

1 Like

Save my day! Works to me!