【问题标题】:Postgres: how to specify parameters in where statement [duplicate]Postgres:如何在where语句中指定参数[重复]
【发布时间】:2021-12-07 20:32:00
【问题描述】:

在 T-SQL 中,我可以像这样在 where 语句中指定参数:

declare @start date set @start ='2021-10-10'
declare @start date set @end ='2021-10-10'

select * 
from dbo.table 
where date between @start and @end

如何在 PostgreSQL 中编写等效语句?

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    解决方案可能取决于您需要使用参数的范围:

    如果作用域只是一个 plpgsql 函数或过程,您可以简单地 DECLARE 您的参数,如 documentation 中所述。

    如果范围是一个事务或会话,您可以在运行时更改和查询配置参数,如documentation 中所述,使用set_configcurrent_setting 函数:

    txt = set_config('myvar.startdate','2021-10-10', false) ;
    txt = set_config('myvar.enddate','2021-10-10', false) ;
    select * 
    from dbo.table 
    where date between current_setting('myvar.startdate') and current_setting('myvar.enddate')
    

    如果范围是多会话,您可以在数据库级别定义配置参数,如documentation 中所述:

    ALTER DATABASE database_name SET myvar.startdate = '2021-10-10' ;
    ALTER DATABASE database_name SET myvar.enddate = '2021-10-10' ;
    select * 
    from dbo.table 
    where date between current_setting('myvar.startdate') and current_setting('myvar.enddate')
    

    您可能需要将配置参数转换为查询中日期列的类型,例如:

    where date between CAST(current_setting('myvar.startdate') AS timestamp with time zone) and CAST(current_setting('myvar.enddate') AS timestamp with time zone)
    

    【讨论】:

      猜你喜欢
      • 2011-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 2011-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多