How to add parameter values to pgadmin sql query?

梦想的初衷 提交于 2021-02-18 04:08:51

问题


In pgadmin3, I would like to use parameterized queries (to faster debugging, just copy & paste the query from my php file). But I haven't found an option to add the values of the $1, $2... parameters. Is it possible?

This is the query I'm building in a loop, following the suggestion for NULL testing from here:

SELECT EXISTS(SELECT 1
              FROM tax
              WHERE (addby=$1 or addby<>$1)
                    AND (adddate=$2 or adddate<>$2)
                    AND ($3 IS NULL AND nome IS NULL OR nome=$3)
                    AND ($4 IS NULL AND rank IS NULL OR rank=$4)
                    AND ($5 IS NULL AND pai IS NULL OR pai=$5)
                    AND ($6 IS NULL AND valido IS NULL OR valido=$6)
                    AND ($7 IS NULL AND sinonvalid IS NULL OR sinonvalid=$7)
                    AND ($8 IS NULL AND espec IS NULL OR espec=$8)
                    AND ($9 IS NULL AND public IS NULL OR public=$9)
       );

Notice that substitute all parameters by hand is tedious, error-prone and probably (I hope) unnecessary.

Thanks in advance.


回答1:


I only know two ways.

First is to use PREPARED STATEMENT (Example after PostgreSQL Manual):

PREPARE usrrptplan (int) AS
    SELECT * FROM users u, logs l
    WHERE u.usrid=$1 AND u.usrid=l.usrid AND l.date = $2;

EXECUTE usrrptplan(1, current_date);

PREPARE creates a prepared statement. When the PREPARE statement is executed, the specified statement is parsed, analyzed, and rewritten. When an EXECUTE command is subsequently issued, the prepared statement is planned and executed.

Prepared statements can take parameters: values that are substituted into the statement when it is executed. When creating the prepared statement, refer to parameters by position, using $1, $2, etc.

Prepared statements only last for the duration of the current database session. When the session ends, the prepared statement is forgotten, so it must be recreated before being used again.

Second is to "find-and-replace" $1, $2, .. etc. by proper values. But you want to avoid this one.




回答2:


In DBeaver you can use parameters in queries just like you can from code, so this will work:

select * from accounts where id = :accountId

When you run the query DBeaver will ask you for the value for :accountId and run the query.



来源:https://stackoverflow.com/questions/32995923/how-to-add-parameter-values-to-pgadmin-sql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!