Postgresql Postgres中contains操作符的实现
如何为字符串实现contains运算符,如果左字符串包含右字符串,则返回true 操作员名称可以是任何名称。我尝试了@并在下面编写了代码,但是Postgresql Postgres中contains操作符的实现,postgresql,operators,plpgsql,contains,Postgresql,Operators,Plpgsql,Contains,如何为字符串实现contains运算符,如果左字符串包含右字符串,则返回true 操作员名称可以是任何名称。我尝试了@并在下面编写了代码,但是 选择'A'@@'SAS' 返回false 如何修复 CREATE OR REPLACE FUNCTION public.contains(searchFor text, searchIn text) RETURNS bool AS $BODY$ BEGIN RETURN position( searchFor in searchIn)<>
选择'A'@@'SAS'
返回false
如何修复
CREATE OR REPLACE FUNCTION public.contains(searchFor text, searchIn text)
RETURNS bool
AS $BODY$ BEGIN
RETURN position( searchFor in searchIn)<>0;
END; $BODY$ language plpgsql immutable RETURNS NULL ON NULL INPUT;
CREATE OPERATOR public.@@ (
leftarg = text,
rightarg = text,
procedure = public.contains
);
按预期返回true
更新
我尝试了9.1代码中的答案:
CREATE OR REPLACE FUNCTION public.contains(searchFor text, searchIn text)
RETURNS bool
LANGUAGE sql IMMUTABLE
AS $BODY$
SELECT position( searchFor in searchIn )<>0;
$BODY$;
CREATE OPERATOR public.<@ (
leftarg = text,
rightarg = text,
procedure = public.contains
);
创建或替换函数public.contains(搜索文本,搜索文本)
返回布尔
语言sql不可变
作为$BODY$
选择位置(在搜索中搜索)0;
$BODY$;
创建运算符公共。PostgreSQL已在PGU目录
架构中的(文本,文本)
上定义了一个@
运算符,该运算符定义为:
regress=> \do @@
List of operators
Schema | Name | Left arg type | Right arg type | Result type | Description
------------+------+---------------+----------------+-------------+-------------------
pg_catalog | @@ | text | text | boolean | text search match
它优先于您在公共
架构中定义的@
我建议使用运算符答案不包含在空输入时返回空值
。是否应将其添加到帮助规划器中?添加换向器、限制、连接、散列、合并
子句是否合理且可行?使用sql语言而不是pgsql更好吗?@Andrus实际上在NULL输入时返回NULL
,STRICT
可以抑制内联,如果可能,最好省略。文件需要更清楚地说明这一点。是的,添加一个换向器@>
操作符是非常合理的。我不知道如何实现哈希。如何仅在运算符不存在时创建它?我尝试了CREATE OPERATOR IF NOT EXISTS public.@Andrus使用DO
块在pg_OPERATOR
中查找它。不是每种语句类型都有(如果不存在)
。就我个人而言,我强烈建议将其打包到扩展中。文档介绍了扩展的创建。扩展不需要任何C代码,它可以是SQL文件、Makefile和扩展控制文件。@Andrus将searchfor替换为$1,将searcin替换为$2
ERROR: column "searchin" does not exist
LINE 5: SELECT position( searchFor in searchIn )<>0;
regress=> \do @@
List of operators
Schema | Name | Left arg type | Right arg type | Result type | Description
------------+------+---------------+----------------+-------------+-------------------
pg_catalog | @@ | text | text | boolean | text search match
CREATE SCHEMA my_operators;
CREATE OR REPLACE FUNCTION my_operators.contains(searchFor text, searchIn text)
RETURNS bool
LANGUAGE sql IMMUTABLE
AS $BODY$
SELECT position( searchFor in searchIn)<>0;
$BODY$;
CREATE OPERATOR my_operators.<@ (
leftarg = text,
rightarg = text,
procedure = public.contains
);
SET search_path = 'my_operators, pg_catalog, public';