PostgreSql Procedure copy split string to table,postgresqlsplit

來源:互聯網
上載者:User

PostgreSql Procedure copy split string to table,postgresqlsplit

我的情境是這樣,有一張表,裡面有一個欄位採用split string存資料。



雖然Hibernate本身提供了 org.hibernate.annotations.Type 注釋,可以通過實現org.hibernate.usertype.UserType來轉換這種可以結果資料,但是使用上並不方便。

為了幹掉這種資料,我採用了mapping表來取代。對於新的資料當然沒有問題,對於曆史資料,需要procedure來同步。這裡分享一個procedure。


主要是引用了 PostgreSql 的 regexp_split_to_table 函數。

regexp_split_to_table(stringtext, pattern text [, flagstext]) setof text Split string using a POSIX regular expression as the delimiter. See Section 9.7.3 for more information. regexp_split_to_table('hello world', E'\\s+') hello

world

(2 rows)
從API描述可以發現,該函數可以將1,2,3這種規則字串以逗號為分隔字元拆分。

先來看一下函數的效果。


剛好滿足我們想要的結果,提供完全的procedure。

DROP FUNCTION IF EXISTS syncRef();CREATE OR REPLACE FUNCTION syncRef() RETURNS void AS$BODY$DECLARE r RECORD;sqlStr text := 'SELECT id,regexp_split_to_table(refIds,'','') as refId from tableA where "length"(refIds) > 0;';BEGINDELETE FROM tableB;FOR r IN EXECUTE sqlStr LOOPIF("length"(r.refId) > 0 AND r.refId != ',')THENINSERT INTO tableB(id,ref_id) VALUES(r.id,cast(r.refId AS BIGINT));END IF;END LOOP;RETURN;END$BODY$LANGUAGE plpgsql ;ALTER FUNCTION syncRef()  OWNER TO db;SELECT syncRef();DROP FUNCTION IF EXISTS syncRef();



對於String類中split方法的問題?

String[] split(String regex)
根據給定的Regex的匹配來拆分此字串。

而Regex中 . 表示匹配任一字元,需要對其轉義

String[] dotR = s.split("\\.");
 
string split()的用法

在java.lang包中有String.split()方法,返回是一個數組
我在應用中用到一些,給大家總結一下,僅供大家參考:
1、如果用“.”作為分隔的話,必須是如下寫法:String.split("\\."),這樣才能正確的分隔開,不能用String.split(".");
2、如果用“|”作為分隔的話,必須是如下寫法:String.split("\\|"),這樣才能正確的分隔開,不能用String.split("|");
“.”和“|”都是逸出字元,必須得加"\\";
3、如果在一個字串中有多個分隔字元,可以用“|”作為連字號,比如:“acount=? and uu =? or n=?”,把三個都分隔出來,可以用String.split("and|or");
使用String.split方法分隔字串時,分隔字元如果用到一些特殊字元,可能會得不到我們預期的結果。
我們看jdk doc中說明

public String[] split(String regex) Splits this string around matches of the given regular expression. 參數regex是一個 regular-expression的匹配模式而不是一個簡單的String,他對一些特殊的字元可能會出現你預想不到的結果,比如測試下面的代碼:

用豎線 | 分隔字串,你將得不到預期的結果

String[] aa = "aaa|bbb|ccc".split("|");
//String[] aa = "aaa|bbb|ccc".split("\\|"); 這樣才能得到正確的結果

for (int i = 0 ; i <aa.length ; i++ ) {
System.out.println("--"+aa[i]);
}

用豎 * 分隔字串運行將拋出java.util.regex.PatternSyntaxException異常,用加號 + 也是如此。

String[] aa = "aaa*bbb*ccc".split("*");
//String[] aa = "aaa|bbb|ccc".split("\\*"); 這樣才能得到正確的結果

for (int i = 0 ; i <aa.length ; i++ ) {
System.out.println("--"+aa[i]);
}

顯然,+ * 不是有效模式比對規則運算式,用"\\*" "\\+"轉義後即可得到正確的結果。

"|" 分隔串時雖然能夠執行,但是卻不是預期的目的,"\\|"轉義後即可得到正確的結果。

還有如果想在串中使用"\"字元,則也需要轉......餘下全文>>
 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.