【发布时间】:2018-12-14 20:01:46
【问题描述】:
我需要创建startswith函数,如果char(n)数据库返回true 列以一些字符开头 may 可以在末尾包含空格。 空格应与其他字符一样处理。
数据库有两个值 'A' 和 'AA' 。我希望 startwith('A') (不带尾随空格)与 AA 和 A 匹配,但 startwith('A') (带尾随空格)仅与 A 匹配。
使用下面的示例数据
startswith( test, 'A') -- works
startswith( test, 'A ') -- returns wrong result : false
StartsWith(test, rpad('A',20) ) -- returns wrong result : false
应该返回真
但是
startswith( test, RPAD( 'A', 21))
应该返回 false,因为检查字符串末尾有多余的空格。
数据库包含具有 char(20) 类型列的测试列,这不能 改变了。
我尝试了下面的代码,但它返回 false。
如何解决这个问题以使其返回 true? 从 9.1 开始使用 Postgres
安德鲁斯。
CREATE or replace FUNCTION public.likeescape( str text )
--
https://stackoverflow.com/questions/10153440/how-to-escape-string-while-matching-pattern-in-postgresql
RETURNS text AS $$
SELECT replace(replace(replace($1,'^','^^'),'%','^%'),'_','^_') ;
$$ LANGUAGE sql IMMUTABLE;
CREATE or replace FUNCTION public.StartWith( cstr text, algusosa text )
RETURNS bool AS $$
SELECT $2 is null or $1 like likeescape($2) ||'%' ESCAPE '^' ;
$$ LANGUAGE sql IMMUTABLE;
create temp table test ( test char(20) ) on commit drop;
insert into test values ('A' );
insert into test values ('AA' );
select StartWith(test, 'A ' ) from test
我也将这个发布到 pgsql-general 邮件列表。
【问题讨论】:
-
我看不出前 3 个示例有什么问题。给定
test= 'A',test以 'A' 开头,不以 'A' 开头,也不以 'A ...' 开头。为什么不正确? -
char(20) 用尾随空格填充。所以
A必须匹配。数据库有两个值 'A' 和 'AA' 。我希望 startwith('A') 返回 AA 和 A 但 startwith('A ') 只返回 A。我更新了问题 -
这是不正确的。
CREATE TEMP TABLE t (txt CHAR(20)); INSERT INTO t VALUES ('A'); SELECT '_' || txt || '_' FROM t;返回_A_,SELECT LENGTH(txt) FROM t;返回1
标签: postgresql plpgsql postgresql-9.1