如何向SQL语句添加引用

时间:2014-08-06 13:29:19

标签: sql psql

我的目标是获取公共架构中具有基本计数的所有表的报告:

这就是我想要做的事情:

SQL:

SELECT 'select '||tablename||' as table_name, count(*) from '||tablename||' UNION ALL'
FROM pg_tables 
WHERE schemaname IN ('public') 
ORDER BY schemaname, tablename;

样本结果:

select foo as table_name, count(*) from foo UNION ALL
select bar as table_name, count(*) from bar UNION ALL
select baz as table_name, count(*) from baz UNION ALL

我想简单地复制上面的结果(没有上一个union all)并将其粘贴到屏幕上以获取报告。看起来像这样:

     table_name      | count 
---------------------+-------
     foo             |  2436
     bar             |  1111
     baz             |  3333
(3 row)

但我的问题是我不知道如何将'放在第一次引用表名的位置,所以语句如下所示:

select 'foo' as table_name, count(*) from foo UNION ALL
select 'bar' as table_name, count(*) from bar UNION ALL
select 'baz' as table_name, count(*) from baz UNION ALL

1 个答案:

答案 0 :(得分:3)

你应该把双撇号(')如下所示

SELECT 'select '''||tablename||''' as table_name, count(*) from '||tablename||' UNION ALL'
FROM pg_tables 
WHERE schemaname IN ('public') 
ORDER BY schemaname, tablename;