Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres IF on variable

Tags:

postgresql

I'm in the process of learning postgres, I've already found a work around to this problem but I wanted to ask the community if something like this is even possible, maybe my syntax is just off.

DO $$ BEGIN
    IF :MODIFYBY IS NOT NULL THEN
        UPDATE User SET ModifyBy = :MODIFYBY WHERE UserId = :USERID;
        UPDATE Profile SET ModifyBy = :MODIFYBY WHERE UserId = :USERID;
    END IF;
END $$;

Receiving

syntax error at or near ":"

as :MODIFYBY is a parameter to this sql.

How can I test if a parameter is null?

Note: Running on PostgreSQL 9.6

Update:

It is possible my terminology is not correct. The full sql statement is this

BEGIN;

    UPDATE User
       SET Email = :EMAIL         
          ,ModifyDate = now() at time zone 'utc'
    WHERE
        UserId = :USERID;

    UPDATE Profile
       SET FirstName = :FIRSTNAME          
          ,LastName = :LASTNAME          
          ,ModifyDate = now() at time zone 'utc'
    WHERE
        UserId = :USERID;

    DO $$ BEGIN
        IF :MODIFYBY IS NOT NULL THEN
            UPDATE User SET ModifyBy = :MODIFYBY WHERE UserId = :USERID;
            UPDATE Profile SET ModifyBy = :MODIFYBY WHERE UserId = :USERID;
        END IF;
    END $$;

COMMIT;

I added the DO $$ BEGIN and END $$; to get the IF statement to work...

like image 827
Layser Avatar asked Jul 26 '26 09:07

Layser


1 Answers

I think your problem is with the use of : parameters in a function doesn't use it.

This is an example of a function using IF

CREATE OR REPLACE FUNCTION traffic.check_distance(
    int_route_source_id bigint,
    num_distance_geo numeric)
RETURNS boolean AS
$BODY$
DECLARE
    bol_route_error boolean = false;
    num_distance_rto numeric;

BEGIN

    -- CALCULATE ROUTE DISTANCE
    SELECT INTO num_distance_rto 
    ....

    --RAISE DISTANCE ALARM 
    IF num_distance_rto > 3.5 * num_distance_geo THEN
        UPDATE traffic.Route_Sources        
        SET 
            IsValid = FALSE,
            result = '3.5x MUY LARGO'
        WHERE 
            route_source_id = int_route_source_id;   
        bol_route_error = true;
    END IF;

    RETURN bol_route_error;

END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION traffic.check_distance(bigint, numeric)
  OWNER TO postgres;
like image 54
Juan Carlos Oropeza Avatar answered Jul 28 '26 03:07

Juan Carlos Oropeza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!