如何使用动态顺序生成sql select

时间:2018-02-28 14:17:52

标签: sql oracle

我需要将不同数据库的内容与相同的表进行比较。他们中的一些人的行数很少,所以我虽然可以直观地比较他们的行列。

所以我试图以下列形式生成一个sql命令:

select * from [tablename] order by 1,2,etc

到目前为止,我已经:

select 'select * from ' || ut.table_name || ' order by ' ||
       (select listagg(num,', ') within group(order by num) csv
          from (        select rownum num
                          from dual
              connect by level <= (select count(*) c
                                     from user_tab_columns
                                    where table_name = 'TABLE99')
                       ))
  from user_tables ut
 where ut.table_name = 'TABLE99';

生成:

select * from TABLE99 order by 1, 2, 3, 4

我想加入table_name上的user_tables和user_tab_columns,这样我就可以为架构中的所有表生成它。不幸的是,简单地做table_name = ut.table_name并不起作用。

如何加入user_tables和user_tab_columns?

1 个答案:

答案 0 :(得分:0)

请改用此查询。我将使用row_number()计算每个表的列数。希望这可以帮助。感谢。

select 'select * from ' || ut.table_name || ' order by ' ||
      listagg(num,', ') within group(order by num) query
from (
  select table_name,
         row_number() over (partition by table_name order by col_name) as num
  from user_tab_columns) t, user_tables ut
where ut.table_name=t.table_name  
group by ut.table_name  
order by ut.table_name 

Result:
query
select * from TABLE99 order by 1, 2, 3, 4
select * from TABLE98 order by 1, 2
相关问题