人大金仓数据库KingbaseES query _to_xml函数使用技巧

102 阅读2分钟

金仓数据库KingbaseES query _to_xml函数使用技巧

关键字:

KingbaseES、query_to_xml、sql、xml、query、人大金仓

XML数据类型

数据类型可以被用来存储XML数据。它比直接在一个text域中存储XML数据的优势在于,它会检查输入值的结构是不是良好,并且有支持函数用于在其上执行类型安全的操作。KingbaseES支持将关系表内容映射为XML类型的数据,提供了一些内置函数,例如query_to_xml、table_to_xml、cursor_to_xml,其中,query_to_xml函数的功能为将sql查询结果转化为XML文档。下文详细介绍了query_to_xml函数的使用。

二、query_to_xml

2.1 语法

query_to_xml(query text, nulls boolean, tableforest boolean, targetns text)

  • 参数详解:
  • query:sql查询字符串,例如:‘select * from test’。
  • nulls:决定空值是否会被包含在输出中。如果为真,列中的空值被表示为:,其中xsi是 XML 模式实例的 XML 名字空间前缀。一个合适的名字空间声明将被加入到结果值中。如果为假,包含空值的列将被从输出中忽略掉。
  • tableforest:决定xml文档输出形式。如果tableforest为假,则结果的 XML 文档看起来像这样:

data

data

...

...

如果tableforest为真,结果是一个看起来像这样的 XML 内容片断:

data

data

...

  • targetns:指定想要的结果的 XML 名字空间。值得注意的是,该参数不能为空,如果设置为空串,得到的XML文档会为空。
  • 返回值:
  • XML类型的数据。

2.2 使用

(1)数据准备:

create table test1 (id int, name text);

insert into test1 values(1, 'aaa'), (2, 'bbb'), (3, null);

(2)函数的调用方式:

  • 方式一:

test=# select query_to_xml('select * from test1', false, false, 'kes');

query_to_xml

---------------------------------------------------------------------------

+

+

1 +

aaa +

+

+

2 +

bbb +

+

+

3 +

+

+

(1 行记录)

  • 方式二:

test=# select * from query_to_xml('select * from test1', false, false, 'kes');

query_to_xml

---------------------------------------------------------------------------

+

+

1 +

aaa +

+

+

2 +

bbb +

+

+

3 +

+

+

(1 行记录)

(3)函数的参数设置:

  • nulls设置为true:

test=# select * from query_to_xml('select * from test1', true, false, 'kes');

query_to_xml

---------------------------------------------------------------------------

+

+

1 +

aaa +

+

+

2 +

bbb +

+

+

3 +

+

+

+

(1 行记录)

  • tableforest设置为true:

test=# select * from query_to_xml('select * from test1', false, true, 'kes');

query_to_xml

-------------------------------------------------------------------------

+

1 +

aaa +

+

+

2 +

bbb +

+

+

3 +

+

(1 行记录)

(4)将xml文档写入文件:

  • 如果文件默认为tsv模式,换行符\n显示在输出结果中:

test=# copy(select query_to_xml('select * from test1 where id=3', false, false, 'kes')) to stdout;

\\n\\n\\n 3\\n\\n\\n
\\n
  • 如果文件为csv模式,换行符\n则用于换行,不会显示在输出结果中:

test=# copy(select query_to_xml('select * from test1 where id=3', false, false, 'kes')) to stdout csv;

"<table xmlns:xsi=""www.w3.org/2001/XMLSch…"" xmlns=""kes"">

3

"

参考文档:

《KingbaseES SQL语言参考手册》