使用 Xmltable postgres 在 xml 的临时 table 中插入值

Insert values in temporary table from xml using Xmltable postgres

我正在尝试将 xml 个节点作为参数传递并从中提取值并将它们插入到 table 中。如果我传递整个 xml 节点,我可以这样做,但如果我尝试通过变量传递它,我将面临语法错误。由于我将拥有需要解析的动态 xml,因此我必须仅通过变量传递它。我在下面提供了我要实现的目标的简化版本。我收到语法错误 'syntax error at or near "xmlvalue"'

CREATE TEMPORARY TABLE SAMPLE(Id text,Author text,Title text);
xmlvalue text := '<Book><Id>1</Id><Author>Subhrendu</Author><Title>Postgre</Title></Book>';
with data as ( 
select xmlvalue::xml val)
--select '<Book><Id>1</Id><Author>Subhrendu</Author><Title>Postgre</Title></Book>'::xml val)
INSERT INTO SAMPLE(Id, Author,Title)
SELECT Id, Author,Title 
FROM   data x, 
XMLTABLE('/Book' 
PASSING val 
COLUMNS  
Id    text  PATH 'Id', 
Author text  PATH 'Author', 
Title text PATH 'Title' )   
; 
select * from sample 

编辑 1:正如建议的那样,我现在尝试将上面的代码包装在一个函数中,因为我们不能在 procedures/functions.

之外使用变量
create or replace function xml()
returns table(Id text,Author Text,Title Text)
as $$
declare
xmlvalue text := '<Book><Id>1</Id><Author>Subhrendu</Author><Title>Postgre</Title></Book>';
begin
CREATE TEMPORARY TABLE SAMPLE(Id text,Author text,Title text);
with data as ( 
select xmlvalue::xml val)
INSERT INTO SAMPLE(Id, Author,Title)
SELECT Id, Author,Title 
FROM   data x, 
XMLTABLE('/Book' 
PASSING val 
COLUMNS  
Id    text  PATH 'Id', 
Author text  PATH 'Author', 
Title text PATH 'Title' )   
; 
return query
select s.Id,s.Author,s.Title from sample s ;
end;
$$
language plpgsql

在尝试执行上述功能时出现以下错误。我从错误中了解到我必须提供 table 别名来引用列。

ERROR:  column reference "id" is ambiguous
LINE 4: SELECT Id, Author,Title 
               ^
DETAIL:  It could refer to either a PL/pgSQL variable or a table column.
QUERY:  with data as ( 
select xmlvalue::xml val)
INSERT INTO SAMPLE(Id, Author,Title)
SELECT Id, Author,Title 
FROM   data x, 
XMLTABLE('/Book' 
PASSING val 
COLUMNS  
Id    text  PATH 'Id', 
Author text  PATH 'Author', 
Title text PATH 'Title' )
CONTEXT:  PL/pgSQL function xml() line 6 at SQL statement
SQL state: 42702

这有效。

create or replace function xml()
returns table(Id text,Author Text,Title Text)
as $$
declare
xmlvalue text := '<Book><Id>1</Id><Author>Subhrendu</Author><Title>Postgre</Title></Book>';
begin
CREATE TEMPORARY TABLE SAMPLE(Id text,Author text,Title text);

with data as ( 
select xmlvalue::xml val)
INSERT INTO SAMPLE(Id, Author,Title)

SELECT d.Id,d.Author,d.Title 
FROM   data x, 
XMLTABLE('/Book' 
PASSING val 
COLUMNS  
Id    text  PATH 'Id', 
Author text  PATH 'Author', 
Title text PATH 'Title' ) as d
; 
return query
select s.Id,s.Author,s.Title from sample s ;
end;
$$
language plpgsql