暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Oracle 常规SQL查询中的动态SQL

askTom 2018-02-21
287

问题描述

嗨,请原谅我问这个问题 (我知道我可以在PL/SQL函数的帮助下做到这一点),但我想问一下以防万一。我想知道这在不使用函数的常规SQL语句中是否可行?我正在尝试查看是否可以编写查询而无需创建函数。

select username
,('select count(*) from '||username||'.'||XYZ) CNT  
from all_users 
where username in ('SCOTT1','SCOTT2');


谢谢,
赫克托


专家解答

所以你试图计算存在于许多模式中的表名的行?你需要动态的任何特殊原因?

无论如何,您可以使用一些XML来完成此操作

dbms_xmlgen.getxmltype接受SQL查询的文本,运行它并将输出返回为XML:

grant unlimited tablespace to u1 identified by u1;
grant unlimited tablespace to u2 identified by u2;
create table u1.t (
  x int
);
create table u2.t (
  x int
);

insert into u1.t values (1);
commit;

select username,
       dbms_xmlgen.getxmltype(' 
  select count(*) c
  from   ' || username || '.t
') x
from   dba_users
where  username in ('U1', 'U2');

USERNAME                       X
------------------------------ ------------------------------
U2                             
                                 
                                   0
                                 
                               

U1                             
                                 
                                   1
                                 
                               


为了获得这些值,你只需要一点XML操作:

with rws as (
  select username,
         dbms_xmlgen.getxmltype(' 
    select count(*) c
    from   ' || username || '.t
  ') x
  from   dba_users
  where  username in ('U1', 'U2')
)
  select username, ct
  from   rws, xmltable (
    '/ROWSET/ROW' passing rws.x
    columns ct integer path '/C'
  );

USERNAME   CT   
U2            0 
U1            1 


尽管问自己: 你真的需要这样做吗?你不能使用静态SQL吗?
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论