我必须在函数中执行以下查询:

SELECT year FROM tbl_people WHERE personal_card = 'A5B123';

它返回一个整数。
问题是,我必须做以下工作:
EXECUTE 'SELECT year FROM tbl_people WHERE personal_card = 'A5B123'';

但它将查询截断为:
SELECT year FROM tbl_people WHERE personal_card

我试过:
EXECUTE "SELECT year FROM tbl_people WHERE personal_card = 'A5B123'";

但也失败了。
我怎样才能做到?

最佳答案

SQL中的单引号are escaped by doubling them

EXECUTE 'SELECT year FROM tbl_people WHERE personal_card = ''A5B123''';

但是在Postgres中做这种事情的一个更方便的方法是使用dollar quoted strings
EXECUTE $$SELECT year FROM tbl_people WHERE personal_card = 'A5B123'$$;

关于postgresql - 使用函数内部的字符串执行查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33786180/

10-16 17:31