ITPub博客

首页 > 数据库 > PostgreSQL > PostgreSQL DBA(73) - dump函数

PostgreSQL DBA(73) - dump函数

原创 PostgreSQL 作者:husthxd 时间:2019-08-12 11:10:08 0 删除 编辑

Oracle提供了dump函数显示字段的十六进制值,PostgreSQL可通过to_hex函数来进行模拟.

Oracle
测试脚本:


TEST-orcl@DESKTOP-V430TU3>CREATE TABLE t_dumpdemo(description varchar(200));
Table created.
TEST-orcl@DESKTOP-V430TU3>
TEST-orcl@DESKTOP-V430TU3>INSERT INTO t_dumpdemo VALUES('中文');
1 row created.
TEST-orcl@DESKTOP-V430TU3>INSERT INTO t_dumpdemo VALUES('ABCDE');
1 row created.
TEST-orcl@DESKTOP-V430TU3>
TEST-orcl@DESKTOP-V430TU3>SELECT * FROM t_dumpdemo;
DESCRIPTION
--------------------------------------------------------------------------------
中文
ABCDE

dump十六进制值


TEST-orcl@DESKTOP-V430TU3>select dump(description,1016) from t_dumpdemo;
DUMP(DESCRIPTION,1016)
--------------------------------------------------------------------------------
Typ=1 Len=4 CharacterSet=ZHS16GBK: d6,d0,ce,c4
Typ=1 Len=5 CharacterSet=ZHS16GBK: 41,42,43,44,45

数据库是用GBK编码,因此’中文’字符编码为GBK编码.

PG
创建dump函数


[local]:5432 pg12@testdb=# CREATE OR REPLACE FUNCTION dump(anynonarray) RETURNS TEXT
pg12@testdb-# LANGUAGE plpgsql
pg12@testdb-# AS
pg12@testdb-# $function$
pg12@testdb$# DECLARE 
pg12@testdb$#   v_hexstr TEXT;
pg12@testdb$#   v_hexbyte TEXT;
pg12@testdb$#   v_tmp TEXT;
pg12@testdb$#   i INT;
pg12@testdb$#   v_len INT;
pg12@testdb$# BEGIN
pg12@testdb$#   SELECT octet_length($1) into v_len;
pg12@testdb$#   v_hexstr := 'Len=' || v_len || ' ';
pg12@testdb$#   v_tmp := ',';
pg12@testdb$#   FOR i in 1..v_len LOOP
pg12@testdb$#     select to_hex(get_byte($1::bytea, i-1)) into v_hexbyte;
pg12@testdb$#     if i = v_len then
pg12@testdb$#       v_tmp := '';
pg12@testdb$#     end if;
pg12@testdb$#     v_hexstr := v_hexstr || v_hexbyte || v_tmp;
pg12@testdb$#   END LOOP;
pg12@testdb$#   -- SELECT encode($1::bytea,'hex') into v_hexbyte;
pg12@testdb$#   -- v_hexstr := v_hexstr||','||v_hexbyte;
pg12@testdb$#   RETURN v_hexstr;
pg12@testdb$# END;
pg12@testdb$# $function$;
CREATE FUNCTION
Time: 3.621 ms

执行dump函数,显示十六进制值


[local]:5432 pg12@testdb=# select dump(description) from t_dumpdemo;
          dump           
-------------------------
 Len=6 e4,b8,ad,e6,96,87
 Len=5 41,42,43,44,45
(2 rows)
Time: 1.337 ms

参考资料
How to display encoded byte stream of a varchar column in PostgreSQL

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/6906/viewspace-2653368/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
ITPUB数据库版块资深版主,对Oracle、PostgreSQL有深入研究。现就职于广州云图数据技术有限公司,系统架构师。

注册时间:2007-12-28

  • 博文量
    1338
  • 访问量
    3804685