简体   繁体   English

使用PERFORM将SELECT语句的字符串插入到临时表中

[英]using PERFORM to insert a string of SELECT statement into a temp table

I am trying to insert data into a temp_table and then truncating the table after analyzing the result. 我正在尝试将数据插入temp_table,然后在分析结果后将其截断。

Here is my code: 这是我的代码:

CREATE OR REPLACE FUNCTION validation()
  RETURNS text AS $$
DECLARE counter INTEGER;
DECLARE minsid INTEGER;
DECLARE maxsid INTEGER;
DECLARE rec RECORD;
DECLARE stmt varchar;
BEGIN
  SELECT MIN(sid) INTO minsid FROM staging.validation;
  SELECT MAX(sid) INTO maxsid FROM staging.validation;

  CREATE TEMPORARY TABLE temp_table (col1 TEXT, col2 INTEGER, col3 BOOLEAN) ON COMMIT DROP;

  FOR counter IN minsid..maxsid LOOP
    RAISE NOTICE 'Counter: %', counter;
    SELECT sql INTO stmt FROM staging.validation WHERE sid = counter;

    RAISE NOTICE 'sql: %', stmt;

    PERFORM 'INSERT INTO temp_table (col1, col2, col3) ' || stmt;

    IF temp_table.col3 = false THEN
      RAISE NOTICE 'there is a false value';
    END IF;

  END LOOP;
END; $$
LANGUAGE plpgsql;

Whenever I run this function SELECT * FROM validation(); 每当我运行此函数SELECT * FROM validation(); I get an error: 我收到一个错误:

ERROR: missing FROM-clause entry for table "temp_table" Where: PL/pgSQL function validation() line 21 at IF

Here is how my staging.validation table looks - 这是我的staging.validation表的外观-

https://docs.google.com/spreadsheets/d/1bXO9gqFS-GtcC1qJtgNbFkR6ygOuPtR_RZoU7VNhgrI/edit?usp=sharing https://docs.google.com/spreadsheets/d/1bXO9gqFS-GtcC1qJtgNbFkR6ygOuPtR_RZoU7VNhgrI/edit?usp=sharing

First, you don't have to use DECLARE for every variable, it's enough with one. 首先,您不必为每个变量都使用DECLARE,一个变量就足够了。

DECLARE
    counter INTEGER;
    minsid INTEGER;
    maxsid INTEGER;
    rec RECORD;
    stmt varchar;

Second, you can't use the temp_table.col3 just like that, you have to query it because it's a table. 其次,不能像这样使用temp_table.col3,因为它是一个表,所以必须对其进行查询。 You could create a variable and query into the table or you could directly make the query. 您可以创建一个变量并查询表,也可以直接进行查询。

Variable: 变量:

-- First you declare de varialbe:
DECLARE
    temp BOOLEAN;

... -- rest of your code

temp := temp_table.col3 FROM temp_table WHERE temp_table.col2=counter;
-- you need something to make the query, here as a test I put col2=counter
IF temp=false THEN
... -- rest of your code

Directly: 直:

... -- rest of your code
IF (SELECT temp_table.col3 FROM temp_table WHERE temp_table.col2=counter)=false THEN
-- Again, you need something to make the query
... -- rest of your code

And third, your function has RETURNS text , in your pl the return is missing; 第三,您的函数具有RETURNS文本 ,在您的pl中缺少返回值;

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

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