我试图将数据插入temp_table,然后在分析结果后截断表。
这是我的代码:
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;
每当我运行此功能
SELECT * FROM validation();
我收到一个错误:
ERROR: missing FROM-clause entry for table "temp_table" Where: PL/pgSQL function validation() line 21 at IF
以下是我的staging.validation表的外观 -
https://docs.google.com/spreadsheets/d/1bXO9gqFS-GtcC1qJtgNbFkR6ygOuPtR_RZoU7VNhgrI/edit?usp=sharing
答案 0 :(得分:3)
首先,您不必为每个变量使用DECLARE,只需使用一个。
DECLARE
counter INTEGER;
minsid INTEGER;
maxsid INTEGER;
rec RECORD;
stmt varchar;
其次,你不能像那样使用temp_table.col3,你必须查询它,因为它是一个表。您可以在表中创建变量和查询,也可以直接进行查询。
变量:
-- 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
直接:
... -- 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
第三,你的函数有 RETURNS text ,在你的pl中缺少回报;