gpt4 book ai didi

sql - 带有包含条件的字符串的 if 语句

转载 作者:行者123 更新时间:2023-11-29 13:36:40 26 4
gpt4 key购买 nike

这个问题是关于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”是作为函数参数提供的变量。

最佳答案

从评论中我终于明白了。你需要dynamic SQL :

CREATE OR REPLACE FUNCTION foo(lastcontact timestamptz)
RETURNS void AS
$func$
DECLARE
myrec record;
mycond boolean;
BEGIN

FOR myrec IN
SELECT * FROM tabel ORDER BY colorlevel, volgnummer
LOOP
IF myrec.conditie ~~ '%lastcontact %' THEN -- special case for input param
myrec.conditie := replace (myrec.conditie
, 'lastcontact '
, CASE WHEN lastcontact IS NULL THEN 'NULL '
ELSE '''' || lastcontact::text || ''' ' END);
END IF;

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
$func$ LANGUAGE plpgsql;

但是请注意,此设置对于SQL 注入(inject) 是完全开放的。仅使用经过验证的输入。函数在 PostgreSQL 8.3 中也有效(还没有 DO 语句)。

您不能在动态 SQL(EXECUTE 语句)中引用参数。您必须将该值放入查询字符串中。

在 PostgreSQL 8.4 或更高版本中,您拥有 USING clause 的优质商品.唉,不是在 8.3 版中。如果可以,您应该考虑升级。

我为您的旧版本提供了解决方法。您必须特别注意 NULL 值。

关于sql - 带有包含条件的字符串的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8893153/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com