动态Postgres查询;错误:运算符不存在:字符变化=整数

时间:2014-03-04 06:03:08

标签: sql dynamic plpgsql execute

我知道这是一个简单/愚蠢的问题,但我在这里苦苦挣扎。 。

运行:在使用Brew安装的OSX上发布9.3 下面的功能给了我这个

错误:运算符不存在:字符变化=整数

提示:没有运算符匹配给定的名称和参数类型。您可能需要添加显式类型转换。

QUERY: SELECT substring(address_postal_code for 5) FROM provider_nodes WHERE npi = $1

CONTEXT: EXECUTE语句中的PL / pgSQL函数测试(整数)第9行

npi_idvarchar表中存储为provider_nodes,但是是一个数字。 无论如何,或者我需要更改类型吗?

CREATE OR REPLACE FUNCTION test(npi_id varchar) RETURNS RECORD AS $$
DECLARE 
zip RECORD;
ptlong RECORD;
ptlat RECORD;
result RECORD;

BEGIN
EXECUTE 'SELECT substring(address_postal_code for 5) FROM provider_nodes WHERE npi = $1' INTO zip;
EXECUTE 'SELECT longitude FROM zctas WHERE zcta=$1' INTO ptlong USING zip;
EXECUTE 'SELECT latitude FROM zctas WHERE zcta=$1' INTO ptlat USING zip;
EXECUTE 'SELECT state, zctas FROM zctas WHERE geom &&   ST_expand(ST_transform(ST_PointFromText("POINT(" || ptlong || " " || ptlat || ")", 4269),32661), 16093) AND ST_distance((ST_transform(ST_PointFromText("POINT(" || ptlong || " " || ptlat || ")", 4269),32661),geom) < 16093' INTO result;
RETURN RESULT;
END;
$$ LANGUAGE plpgsql;

1 个答案:

答案 0 :(得分:0)

在动态SQL中使用参数时,必须使用USING子句。你在第一个陈述中错过了它:

EXECUTE 'SELECT substring(address_postal_code for 5) FROM provider_nodes WHERE npi = $1' INTO zip USING npi_id;

但在这种情况下使用动态SQL(语句EXECUTE)是个坏主意。你可以写

zip := (SELECT substring(p.address_postal_code for 5) 
           FROM provider_nodes p
          WHERE p.npi = npi_id);