【发布时间】:2012-02-12 04:04:48
【问题描述】:
这个问题是关于 Postgresql 8.3。
我有一个表,其中的字段包含“lastcontact 为空”等条件。在代码中,我想遍历这个表,对于每条记录,我想检查'if condition then',就像在这个例子中一样:
FOR myrec IN
SELECT * FROM tabel ORDER BY colorlevel, volgnummer
LOOP
if (myrec.conditie) then
raise notice 'Condition % is true', myrec.conditie;
else
raise notice 'Condition % is false', myrec.conditie;
end if;
END LOOP;
在这个例子中我称之为'tabel'的表:
ID | Conditie | Colorlevel | Volgnummer | Code | Description
1 | lastcontact is null | 1 | 1 | ... | ...
2 | lastchanged is null | 1 | 2 | ... | ...
3 | lastmodified is null | 1 | 3 | ... | ...
是否可以进行我想要的检查?上面的代码导致如下错误:
ERROR: invalid input syntax for type boolean: "lastcontact is null"
包含 Erwin 函数结果的新部分
我用过这个功能:
CREATE OR REPLACE FUNCTION foo(lastcontact timestamptz)
RETURNS void AS
$BODY$
DECLARE
myrec record;
mycond boolean;
BEGIN
FOR myrec IN
SELECT * FROM tabel ORDER BY colorlevel, volgnummer
LOOP
EXECUTE 'SELECT ' || myrec.conditie || ' FROM tabel' INTO mycond;
IF mycond then
RAISE NOTICE 'Condition % is true', myrec.conditie;
ELSE
RAISE NOTICE 'Condition % is false', COALESCE(myrec.conditie, 'NULL');
END IF;
END LOOP;
END;
$BODY$
language 'plpgsql' volatile
cost 100;
我收到此错误:
ERROR: column "lastcontact" does not exist
LINE 1: SELECT lastcontact is null FROM tabel
^
QUERY: SELECT lastcontact is null FROM tabel
CONTEXT: PL/pgSQL function "foo" line 9 at EXECUTE statement1
我试图自己寻找解释,但无济于事。它显然是在尝试对数据库运行该语句,但它应该理解“lastcontact”是作为函数参数给出的变量。
【问题讨论】:
标签: sql postgresql null dynamic-sql plpgsql