首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> Oracle 資料庫 >> Oracle 教學

PostgreSQL 常用字串與日期函數大全:實戰修復資料指南

     編輯:Oracle 教學

PostgreSQL 常用字串與日期函數大全:實戰修復資料指南

資料修復優先在資料庫層完成 (SQL/函數),不可行再考慮外部程式。本文彙整 PostgreSQL 核心字串函數,並以「將微博頭像 URL 中 /50/ 替換為 /180/」實戰案例串聯常用函數。

實戰場景:批次修復圖片 URL

-- 原始:https://tp2.sinaimg.cn/1928431341/50/5621497131/1
-- 目標:https://tp2.sinaimg.cn/1928431341/180/5621497131/1

-- 方法 1:overlay + position
UPDATE t_sns_member
SET enlarge_image_url = overlay(profile_image_url
    PLACING '/180/'
    FROM position('/50/' IN profile_image_url)
    FOR 4)
WHERE enlarge_image_url = '';

-- 方法 2:substring + position + 串接
UPDATE t_sns_member
SET enlarge_image_url =
    substring(profile_image_url, 1, position('/50/' IN profile_image_url) - 1)
    || '/180/'
    || substring(profile_image_url, position('/50/' IN profile_image_url) + 4)
WHERE enlarge_image_url = '';

-- 方法 3:replace (最簡潔)
UPDATE t_sns_member
SET enlarge_image_url = replace(profile_image_url, '/50/', '/180/')
WHERE enlarge_image_url = '';

核心字串函數速查表

函數用途範例
||字串串接'A' || 'B' = 'AB'
length(str) / char_length(str)字元長度length('abc') = 3
octet_length(str)位元組長度octet_length('中') = 3 (UTF8)
substring(str FROM start FOR len)擷取子字串substring('abcdef' FROM 2 FOR 3) = 'bcd'
position(sub IN str)子字串位置 (1-based)position('cd' IN 'abcdef') = 3
strpos(str, sub)同 position,參數順序相反strpos('abcdef', 'cd') = 3
replace(str, from, to)全部替換replace('a_b_c', '_', '-') = 'a-b-c'
overlay(str PLACING new FROM start FOR len)指定位置替換overlay('abcdef' PLACING 'XY' FROM 2 FOR 2) = 'aXYef'
split_part(str, delim, n)分割取第 n 段split_part('a,b,c', ',', 2) = 'b'
trim([BOTH|LEADING|TRAILING] chars FROM str)去除首尾字元trim(BOTH 'x' FROM 'xxaxx') = 'a'
upper(str) / lower(str)大小寫轉換upper('abc') = 'ABC'
initcap(str)每單字首字大寫initcap('hello world') = 'Hello World'
regexp_replace(str, pattern, repl)正則替換regexp_replace('a1b2', '\d', '') = 'ab'
md5(str)MD5 雜湊md5('abc') = '900150983cd24fb0d6963f7d28e17f72'
encode(data, 'base64') / decode(str, 'base64')Base64 編解碼encode('abc', 'base64') = 'YWJj'
to_hex(num)數值轉十六進位to_hex(255) = 'ff'

日期/時間函數補充

  • CURRENT_DATE, CURRENT_TIMESTAMP, NOW()
  • age(timestamp):計算年齡/間隔。
  • date_trunc('month', ts):截斷至月/日/時。
  • EXTRACT(field FROM ts):取得年/月/日/時/分/秒/epoch。
  • ts + interval '3 months':日期運算 (標準 SQL)。

編碼轉換函數

convert(str, src_encoding, dest_encoding)  -- 指定來源/目標編碼
convert_from(str, src_encoding)            -- 轉為資料庫編碼
convert_to(str, dest_encoding)             -- 從資料庫編碼轉出
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved