如何使用ora:view针对另一个模式编写XQUERY调用

时间:2019-05-09 16:20:57

标签: sql oracle xquery-sql

我想在Oracle SQL Developer中编写一个XQUERY调用,但是我一直遇到错误。

我已经创建了一个架构和表:

ALTER SYSTEM SET deferred_segment_creation=false;
CREATE USER bookdb IDENTIFIED BY abc123;
GRANT RESOURCE TO bookdb;
GRANT UNLIMITED TABLESPACE TO bookdb;
ALTER SESSION SET CURRENT_SCHEMA=bookdb;
CREATE SEQUENCE book_id_seq START WITH 1 INCREMENT BY 1; 
CREATE TABLE book (
  id INTEGER NOT NULL PRIMARY KEY,
  title VARCHAR2(50) NOT NULL UNIQUE,
  originallanguage VARCHAR2(20) NOT NULL,
  genre VARCHAR2(20)
 );

这是表中一行的示例:

INSERT INTO book VALUES (book_id_seq.nextval,'Misty Nights','English','Thriller');

该表位于SQL Developer对象导航器的“其他用户”下。

如果我只写SELECT * FROM BOOKDB.BOOK,它就可以工作。但是使用XQUERY命令和ora:view函数对我不起作用。

我要运行的XQUERY命令是:

XQUERY
element Result {
for $lang in distinct-values(ora:view("BOOKDB.BOOK")//ORIGINALLANGUAGE/text())
let $sum := for $book in ora:view("BOOKDB.BOOK")//ORIGINALLANGUAGE
            return $book[text() = $lang]
return element Language {attribute name {$lang}, attribute Total {count($sum)}}}

但是出现以下错误:

Error at Command Line : 1 Column : 9
Error report -
SQL Error: ORA-00942: table or view does not exist
00942. 00000 -  "table or view does not exist"
*Cause:    
*Action:

我的查询有问题吗?还是ora:view函数?

1 个答案:

答案 0 :(得分:1)

您正在将一个参数传递给ora:view,该参数应该是表名。目前,您正试图告诉它使用SQL点表示法(BOOK)在模式BOOKDB中查找名为BOOKDB.BOOK的表,但是您正在使用XML您提供该值时的上下文。如文档所示,您可以使用该函数的可选第一个参数来指定架构:

XQUERY
element Result {
for $lang in distinct-values(ora:view("BOOKDB", "BOOK")//ORIGINALLANGUAGE/text())
let $sum := for $book in ora:view("BOOKDB", "BOOK")//ORIGINALLANGUAGE
            return $book[text() = $lang]
return element Language {attribute name {$lang}, attribute Total {count($sum)}}}

Result Sequence                                                                 
--------------------------------------------------------------------------------
<Result><Language name="English" Total="1"></Language></Result>

(这基于您添加到问题中的DDL中未加引号的列名,例如originallanguage;而不是您最初发布的图像中表示您已加引号标识符的混合大小写值,例如{{ 1}}。正如评论/聊天中所讨论的,这里"OriginalLanguage"是一个 schema ,而不是数据库;术语的混合令人困惑,因为'DB'是模式名称。)

这只是XMLTable调用的客户端包装,顺便说一句:

BOOKDB

您也可以将其用作XMLQuery:

select column_value from xmltable('element Result {
for $lang in distinct-values(ora:view("BOOKDB", "BOOK")//ORIGINALLANGUAGE/text())
let $sum := for $book in ora:view("BOOKDB", "BOOK")//ORIGINALLANGUAGE
            return $book[text() = $lang]
return element Language {attribute name {$lang}, attribute Total {count($sum)}}}')

此外,select xmlquery('element Result { for $lang in distinct-values(ora:view("BOOKDB", "BOOK")//ORIGINALLANGUAGE/text()) let $sum := for $book in ora:view("BOOKDB", "BOOK")//ORIGINALLANGUAGE return $book[text() = $lang] return element Language {attribute name {$lang}, attribute Total {count($sum)}}}' returning content) from dual 已过时;但是您可以使用ora:view做同样的事情:

fn:collection