简体   繁体   English

postgres - 如何将结果计数分配给变量并基于该变量进行 select 查询

[英]postgres - How to assign a result count to a variable and do a select query based on that

I am a from T-SQL and MS SQL Server background and struggling with PostgreSQL. I need to declare a variable, do a count query, save the result of the count in the variable;我是来自T-SQL和MS SQL服务器后台,正在和PostgreSQL斗争。我需要声明一个变量,做一个计数查询,将计数的结果保存在变量中; then based, on the count assign a date to another variable, and then do a select query with that assigned date to return its result set.然后根据计数将日期分配给另一个变量,然后使用分配的日期执行 select 查询以返回其结果集。 The problem is when I declare a variable without a DO $$ block, like so:问题是当我声明一个没有DO $$块的变量时,如下所示:

DECLARE num_rows bigint; I get:我得到:

ERROR: syntax error at or near "bigint"错误:“bigint”处或附近的语法错误

LINE 1: DECLARE num_rows bigint;第 1 行:声明 num_rows bigint;

And if I try within the DO $$ block, I get the following error on the SELECT :如果我在DO $$块中尝试,我会在SELECT上收到以下错误:

ERROR: query has no destination for result data错误:查询没有结果数据的目的地

HINT: If you want to discard the results of a SELECT, use PERFORM instead.提示:如果您想丢弃 SELECT 的结果,请改用 PERFORM。

CONTEXT: PL/pgSQL function inline_code_block line 35 at SQL statement SQL state: 42601上下文:PL/pgSQL function inline_code_block 第 35 行 SQL 语句 SQL state:42601

This is what I am trying:这就是我正在尝试的:

DO $$
DECLARE num_rows bigint;
DECLARE end_date timestamp with time zone;
BEGIN
SELECT COUNT(my_table.id) 
INTO num_rows
FROM my_table
WHERE my_table.something = 1;

IF num_rows > 500 THEN
end_date = '2022-12-03';
END IF;

SELECT * FROM another_table WHERE some_date < end_date;

END $$;

Is there any way to accomplish this or similar in PostgreSQL?在 PostgreSQL 中有什么方法可以完成这个或类似的事情吗? I cannot use functions because it is a legacy database and I cannot do DDL changes to it.我不能使用函数,因为它是遗留数据库,我不能对其进行 DDL 更改。

1)in row end_date = '2022-12-03' you need a semicolon 1) 在行end_date = '2022-12-03'你需要一个分号

2)in last select statement you must use execute 2)在最后的 select 语句中你必须使用execute

I think this will work:我认为这会起作用:

DO $$
DECLARE 
  num_rows bigint;
  end_date timestamp with time zone;
BEGIN
SELECT COUNT(my_table.id) 
INTO num_rows
FROM my_table
WHERE my_table.something = 1;

IF num_rows > 500 THEN
end_date = '2022-12-03';
END IF;

execute 'SELECT * FROM another_table WHERE some_date <'|| end_date;

END $$;

You can also try to run something like this:你也可以尝试运行这样的东西:

with mydate as(
    select case when (select count(*) from mytable where something = 1)>500 then '2022-12-03' end as end_date,
    (select count(*) from mytable where something = 1) as num_rows
    )
select * from another_table a,mydate b where a.some_date>end_date;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM