1. 程式人生 > >PostgreSQL字串處理函式

PostgreSQL字串處理函式

前期準備,新建資料表

CREATE TABLE mytable

(

id serial NOT NULL,

"name" character varying(20),

geom geometry,

remark character varying(255)

)

插入資料

Insert into mytable(name,geom,remark) values('test1','point(12 23)','remark1');

Insert into mytable(name,geom,remark) values('test2','point(14 23)','remark2');

Insert into mytable(name,geom,remark) values('test3','point(17 23)','remark3');

Insert into mytable(name,geom,remark) values('test4','point(92 29)','remark4');

Insert into mytable(name,geom,remark) values('test5','point(82 83)','remark5');

1、字串連線符 '||'

例子:select name || remark as newname from mytable where name like '%test%';

結果:

newname

"test1remark1"

"test2remark2"

"test3remark3"

"test4remark4"

"test5remark5"

2、字串長度:bit長度bit_length(string),字元長度char_length(string)或者是character_length(string),位元組長度octet(string),具體的長度跟資料庫字元編碼有關,注意中文字元的長度

例子:select name,bit_length(name),char_length(name),octet_length(name) from mytable where name like '%test%';

結果

"test1";40;5;5

"test2";40;5;5

"test3";40;5;5

"test4";40;5;5

"test5";40;5;5

3、字串替換overlay(string placing string from int [for int])

例子:select name,overlay(name placing 'DD' from 5 for 2) from mytable where name like '%test%';

結果

"test1";"testDD"

"test2";"testDD"

"test3";"testDD"

"test4";"testDD"

"test5";"testDD"

4、查詢字串位子position(substring in string)

例子:select name,position('test' in name) from mytable where name like '%test%';

結果:

"test1";1

"test2";1

"test3";1

"test4";1

"test5";1

5、取子串,substring(string [from int] [for int]),substring(string from pattern)

例子1select name,substring(name from 1 for 2) from mytable where name like '%test%';

結果1

"test1";"te"

"test2";"te"

"test3";"te"

"test4";"te"

"test5";"te"

例子2select name,substring(name from '^...') from mytable where name like '%test%';

結果2:以任何三個字元開頭的,以任何兩個字元結尾的為:substring(name from '..$')

"test1";"tes"

"test2";"tes"

"test3";"tes"

"test4";"tes"

"test5";"tes"

6、轉換為大些和小寫:upper(string)lower(string)

例子:select name,upper(name),lower(name) from mytablewhere name like '%test%';

結果:

"test1";"TEST1";"test1"

"test2";"TEST2";"test2"

"test3";"TEST3";"test3"

"test4";"TEST4";"test4"

"test5";"TEST5";"test5"

7、去除開頭或者結尾或者全部的包含的字串trim([leading|trailing|both] [characters] from string)

例子:select name,trim(name),trim(leading 'test' from name),trim('1' from name) from mytablewhere name like '%test%';

結果:

"test1";"test1";"1";"test"

"test2";"test2";"2";"test2"

"test3";"test3";"3";"test3"

"test4";"test4";"4";"test4"

"test5";"test5";"5";"test5"