Debug SQL in pgAdmin when SQL contains variables

前端 未结 3 510
臣服心动
臣服心动 2021-02-06 13:11

In SQL Server I could copy sql code out of an application and paste it into SSMS, declare & assign vars that exist in the sql and run. yay great debugging scenario.

相关标签:
3条回答
  • 2021-02-06 13:25

    SQL procs are notoriously hard to debug. My lame but practical solution has been to write log messages to a log table, like this (please excuse syntax issues):

    create table log_message (
      log_timestamp timestamp not null default current_timestamp,
      message varchar(1000)
    );
    

    then add lines to your stored proc like:

    insert into log_message (message) values ("The value of x is " || @x);
    

    Then after a run:

    select * from log_message order by 1;
    

    It's not pretty, but works in every DB.

    0 讨论(0)
  • 2021-02-06 13:44

    You can achieve this using the PREPARE, EXECUTE, DEALLOCATE commands for handling statements, which is really what we are talking about here.

    For example:

    PREPARE test AS SELECT * FROM users WHERE first_name = $1;
    EXECUTE test ('paul');
    DEALLOCATE test;
    

    Perhaps not as graphical as some may like, but certainly workable.

    0 讨论(0)
  • 2021-02-06 13:46

    I would give a shot at writing a SQL function that wraps your query. It can be something as simple as

    CREATE OR REPLACE FUNCTION my_function(integer, integer) 
    RETURNS integer
    AS
    $$
        SELECT $1 + $2;
    $$ 
    LANGUAGE SQL;
    
    SELECT my_function(1, 2);
    

    I would do this instead of a PREPARE since it will be simpler to update it. Depending on how complex the function is, you might want to also look at some of the other PL's in Postgres.

    0 讨论(0)
提交回复
热议问题