在函数内执行带字符串的查询

时间:2015-11-18 17:10:54

标签: postgresql postgresql-9.4

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

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'";

但也失败了。

我怎样才能实现它?

2 个答案:

答案 0 :(得分:3)

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'$$;

答案 1 :(得分:2)

您可以使用quote_literal这样的功能:

EXECUTE 'SELECT year FROM tbl_people WHERE personal_card = ' || quote_literal('A5B123');