Count(*) for all tables
Hi ,
I want the Query to get the table name and count(*) display in excel like this.Can i get count(*) from metadata table .Please let me know ??
ACCT 53
ACCT_CHEQUE 45
EMP 50
DEPT 90
Karthick_Arp wrote:
A XML solution.
This one is not mine. This question comes up often in this forum. And once i saw this answer. And i thought its really cool so just saved it in my Google Note Book ;)You need to update your google note book. It doesn't take account of Index Organised Tables.
Based on answer from Laurent Schneider
http://laurentschneider.com/wordpress/2007/04/how-do-i-store-the-counts-of-all-tables.html
SQL> select
2 table_name,
3 to_number(
4 extractvalue(
5 xmltype(
6 dbms_xmlgen.getxml('select count(*) c from '||table_name))
7 ,'/ROWSET/ROW/C')) count
8 from user_tables
9 where iot_type != 'IOT_OVERFLOW';
TABLE_NAME COUNT
DEPT 4
EMP 14
BONUS 0
SALGRADE 5Edited by: BluShadow on Jul 8, 2009 12:00 PM
Similar Messages
-
Trying to get row counts for all tables at a time
Hi,
i am trying to get row counts in database at a time with below query but i am getting error:
its giving me ora-19202 error..please advise me
select
table_name,
to_number(
extractvalue(
xmltype(dbms_xmlgen.getxml('select count(*) c from '||table_name))
,'/ROWSET/ROW/C')
count
from all_tables;ALL_TABLES returns tables/views current user has access to. These tables/views are owned not just by current user. However your code
dbms_xmlgen.getxml('select count(*) c from '||table_name)does not specify who the owner is. You need to change it to:
dbms_xmlgen.getxml('select count(*) c from '||owner || '.' || table_name)However, it still will not work. Why? As I said, ALL_TABLES returns tables/views current user has access to. Any type of access, not just SELECT. So if current user is, for example, granted nothing but UPDATE on some table the above select will fail. You would have to filter ALL_TABLES through ALL_SYS_PRIVS, ALL_ROLE_PRIVS, ALL_TAB_PRIVS and PUBLIC to get list of tables current user can select from. For example, code below does it for tables/views owned by current user and tables/views current user is explicitly granted SELECT:
select
t.owner,
t.table_name,
to_number(
extractvalue(
xmltype(dbms_xmlgen.getxml('select count(*) c from '||t.owner || '.' || t.table_name))
,'/ROWSET/ROW/C')
count
from all_tables t,user_tab_privs p
where t.owner = p.owner
and t.table_name = p.table_name
and privilege = 'SELECT'
union all
select
user,
t.table_name,
to_number(
extractvalue(
xmltype(dbms_xmlgen.getxml('select count(*) c from '||t.table_name))
,'/ROWSET/ROW/C')
count
from user_tables t
OWNER TABLE_NAME COUNT
SCOTT DEPT 4
U1 QAQA 0
U1 TBL 0
U1 EMP 1
SQL> SY. -
How to get row count(*) for each table that matches a pattern
I have the following query that returns all tables that match a pattern (tablename_ and then 4 digits). I also want to return the row counts for these tables.
Currently a single column is returned: tablename. I want to add the column RowCount.
DECLARE @SQLCommand nvarchar(4000)
DECLARE @TableName varchar(128)
SET @TableName = 'ods_TTstat_master' --<<<<<< change this to a table name
SET @SQLCommand = 'SELECT [name] as zhistTables FROM dbo.sysobjects WHERE name like ''%' + @TableName + '%'' and objectproperty(id,N''IsUserTable'')=1 ORDER BY name DESC'
EXEC sp_executesql @SQLCommandThe like operator requires a string operand.
http://msdn.microsoft.com/en-us/library/ms179859.aspx
Example:
DECLARE @Like varchar(50) = '%frame%';
SELECT * FROM Production.Product WHERE Name like @Like;
-- (79 row(s) affected)
For variable use, apply dynamic SQL:
http://www.sqlusa.com/bestpractices/datetimeconversion/
Rows count all tables:
http://www.sqlusa.com/bestpractices2005/alltablesrowcount/
Kalman Toth Database & OLAP Architect
SQL Server 2014 Design & Programming
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012 -
GETTING ROW COUNTS OF ALL TABLES AT A TIME
Is there any column in any Data dictionary table which gives the row counts for particular table..
My scenario is...i need to get row counts of some 100 tables in our database...
instead of doing select count(*) for each table....is there any way i can do it?
similary How to get column counts for each table..in database .For example
Employee table has 3 columns...empid,empname,deptno....i want count(empid),
count(empname),count(deptno) ...is there any easy way for finding all column counts of each table in data base? is it possible?Why does "select count(mgr) from emp" return null and not 13?Good question ;)
Seems that xml generation in principle can't handle »counting nulls«:
SQL> select xmltype(cursor(select null c from dual)) x from dual
X
<?xml version="1.0"?>
<ROWSET>
<ROW>
</ROW>
</ROWSET>
1 row selected.
SQL> select cursor(select count(null) c from dual) x from dual
Cur
0
1 row selected.
SQL> select xmltype(cursor(select count(null) c from dual)) x from dual
select xmltype(cursor(select count(null) c from dual)) x from dual
Error at line 1
ORA-31011: XML parsing failed
ORA-19202: Error occurred in XML processing
LPX-00229: input source is empty
Error at line 0
ORA-06512: at "SYS.XMLTYPE", line 0
ORA-06512: at line 1
but
SQL> select xmltype(cursor(select count(1) c from dual)) x from dual
X
<?xml version="1.0"?>
<ROWSET>
<ROW>
<C>1</C>
</ROW>
</ROWSET>
1 row selected.Looks like a bug to me ... -
Get records count of all tables
Hi ,
I am trying to get the record count of all tables using dynamic query. I don't know how to put the value in placeholder. I tried the below code.
SET SERVEROUTPUT ON SIZE 1000000
DECLARE
CURSOR table_list
IS
select OBJECT_NAME from user_objects
where object_type in ('TABLE')
and object_name not like '%AUDIT_DDL%'
AND object_name not like 'MD_%'
AND object_name not like 'EXT_%'
AND object_name not like 'STG_%'
AND object_name not like 'SYS_%'
AND object_name not like 'TMP_%'
AND object_name not like 'TEMP_%'
order by 1;
v_count NUMBER :=0;
query_str VARCHAR2(1000);
BEGIN
FOR table_name IN table_list
LOOP
query_str :='SELECT COUNT(1) FROM ' || table_name.OBJECT_NAME;
dbms_output.put_line(query_str);
dbms_output.put_line('Table Name:' || table_name.OBJECT_NAME );
v_count:= execute immediate query_str;
dbms_output.put_line('Table Name:' || table_name.OBJECT_NAME || ', Count ' || v_count );
END LOOP;
END;
I know I am doing wrong in the bold lines. But not sure how to fix it. Please help. Thanks in advance.Hi,
Welcome to the forum!
What you posted is basically right, assuming you really want to do dynamic SQL t all.
The only problem with
961618 wrote:
query_str :='SELECT COUNT(1) FROM ' || table_name.OBJECT_NAME; would be if the object name included special characters (such as single-quotes) or lower-case letters. To avoid any possible problems, I would put the object name inside double-quotes:
... query_str := 'SELECT COUNT (*) FROM "' || table_name.OBJECT_NAME
|| '"';
v_count:= execute immediate query_str;
The correct syntax is
execute immediate query_str INTO v_count;V_count will be the number of rows in a single table. Keep another variable (say total_v_count) that keeps the total count so far.
Do you really need dynamic SQL?
SELECT SUM (num_rows) AS total_rows
FROM user_tables
WHERE table_name NOT_LIKE '%AUDIT_DDL%
AND ...
;gets the same information, accurate as of the last time statistics were gathered, and some of the numbers may be approximate. Depending on how you use the results, that may be good enough for you. If you actually have 10,000,123 rows, and the query says you have 10,000,000, does it really matter? -
How do I run sp_spaceused for all tables in a database?
Hi,
I am struggling to understand how to run the sp_spaceused sproc for all tables in a database.
I know how to use it for one table but how would I replicate it automatically for each table in a given database?
Regards,
Ian.I just managed to alter the code of VidyaSagar and have pulled out all the information including Schema name. Below is what it looks like:
set
nocount
on
select
'Database Name: ',
db_name
if
exists(select
name from tempdb..sysobjects
where name='##tmp'
drop
table ##tmp
create
table ##tmp(TABLE_SCHEMA
nvarchar(256),TABLE_NAME
nvarchar(256),
num_rows int,
reserved_KB varchar(15),data_KB
varchar(15),index_KB
varchar(15),unsed_KB
varchar(15
go
declare
@tbl_schema nvarchar(256
declare
@tbl_name nvarchar(256
declare
@schema_tbl_name nvarchar(256
declare
tblname CURSOR
for
select
TABLE_SCHEMA
TABLE_NAME
from
INFORMATION_SCHEMA.TABLES
where TABLE_TYPE='BASE
TABLE'
open
tblname
Fetch
next
from tblname
INTO @tbl_schema,@tbl_name
WHILE
@@FETCH_STATUS
= 0
BEGIN
set @schema_tbl_name=@tbl_schema+'.'+@tbl_name
insert
into ##tmp(TABLE_NAME
, num_rows
, reserved_KB
,data_KB
,index_KB
,unsed_KB
exec
sp_spaceused
@schema_tbl_name
update ##tmp
set TABLE_SCHEMA
=@tbl_schema
where TABLE_SCHEMA
is
NULL
and TABLE_NAME=@tbl_name
FETCH
NEXT
FROM tblname
INTO @tbl_schema,@tbl_name
END
CLOSE
tblname
deallocate
tblname
go
select
from
##tmp
drop
table ##tmp
Warm Regards, Ajay -
Get row count for different tables to the same line
How can I get the row count for different tables in one line:
SELECT count(A), count(B), count(C) from table tb_a A , tb_b B, tb_c C;
Thanks!>
Hi,
How can I get the row count for different tables in one line:
SELECT count(A), count(B), count(C) from table tb_a A , tb_b B, tb_c C;Something like this? One of the many uses for CTE's - Common Table Expressions - AKA
subquery refactoring. Worth getting to know - very handy!
with acount as
select count(*) as counta from dual -- put your table name here
bcount as
select count(*) as countb from dual -- put your table name here
ccount as
select count(*) as countc from dual -- put your table name here
select a.counta, b.countb, c.countc from acount a, bcount b, ccount c;HTH,
Paul...
Edited by: Paulie on 25-Jul-2012 17:44 -
Extract schema/metadata - names for all tables and attributes
Hi, I am quite new to Oracle DB (only been doing dev mostly with sqlserver before). Is there a way to extract schema (names for all tables and attributes) for 10g and 11g in application code (either java or .net) or pl/sql?
Thank you,
-TonyThere are built in views that start with DBA_, ALL_, and USER_. All means all the user can see, user means all the user has, and dba means everything, which generally means the same as the others plus an owner. So you can desc user_tables to see what-all that view has, then select columns from the view with ordinary sql. See the doc set for all the views available, interesting ones are ...views, ...objects, ...tab_cols and so forth.
There are also built in procedures for getting metadata, google for details.
Many tools have easy GUI's for this too. EM has ways on the administration screen to get to various objects, and then you can show the ddl. Maybe sqldeveloper has something too. -
Count number of distinct values for a column for all tables that contains that column
Imagine I have one Column called cdperson. With the query below I know which Tables have column cdperson
select
t.[name]fromsys.schemassinnerjoin
sys.tables
tons.schema_id=t.schema_idinnerjoin
sys.columnscont.object_id=c.object_idinnerjoin
sys.types
donc.user_type_id=d.user_type_idwherec.name ='cdperson'
now I want to know for each table, how many distinct values of cdperson I have and I want the result ordered by the table that has more distinct values (descending)
Table1
cdperson select distinct(cdperson) = 10
cdadress
quant
Table2 with
cdaddress (no column cdperson in this table)
quant
Table3
cdperson select distinct(cdperson) = 100
value
Table 4
cdperson select distinct(cdperson) = 18
sum
I want this result ordered by number of distinct cdperson
table3 100
table4 18
table 10
Thks for your answersI had to add schema name to the above script to make it work in AdventureWorks:
CREATE TABLE #temp(TableName sysname , CNT BIGINT)
DECLARE @QRY NVARCHAR(MAX);
SET @qry=(SELECT
N'INSERT INTO #TEMP SELECT '''+schema_name(t.schema_id)+'.'+T.[name] +''' AS TableName, COUNT (DISTINCT ProductID) DistCount FROM '+
schema_name(t.schema_id)+'.'+t.[name] +';'
FROM sys.schemas s INNER JOIN sys.tables t ON s.schema_id=t.SCHEMA_ID
INNER JOIN sys.columns c ON t.object_id=c.object_id INNER JOIN sys.types d ON c.user_type_id=d.user_type_id
WHERE c.name ='ProductID'
FOR XML PATH(''))
EXEC(@QRY)
SELECT * FROM #temp ORDER BY TableName
DROP TABLE #temp
Production.Product 504
Production.ProductCostHistory 293
Production.ProductDocument 31
Production.ProductInventory 432
Production.ProductListPriceHistory 293
Production.ProductProductPhoto 504
Production.ProductReview 3
Production.TransactionHistory 441
Production.TransactionHistoryArchive 497
Production.WorkOrder 238
Production.WorkOrderRouting 149
Purchasing.ProductVendor 211
Purchasing.PurchaseOrderDetail 211
Sales.SalesOrderDetail 266
Sales.ShoppingCartItem 3
Sales.SpecialOfferProduct 295
Kalman Toth Database & OLAP Architect
SQL Server 2014 Database Design
New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014 -
How to tcack the table update event in sap for all tables by use of single
Hello,
I want to store the list of all OM,HR tables in a file which are updated after perticular date. For that i tried TRIGGER but i can write only one trigger for one table, i want such a that i have to write only one trigger which will be invoked affter update operation on every HR,OM tables and i store information in a file regarding which rows are updated and external application can use it.
Thanks in advance,
SANDIPhi all the log for the change of any thing will be available in the tables DBTABLOG..REPOSRC ....
regards,
venkat. -
Creating sequences for all tables in the database at a time
Hi ,
I need to create sequences for all the tables in my database.
i can create individually ,using toad and sqlplus.
Can any one give me a code for creating the sequences dynamically at a time for all the tables.
it is urgent ..
Regards.I need to create sequences for majority of the tables that are having ID column
which is sequences."The majority" is not the same as all. So you probably want to drive your generation script off the ALL_TAB_COLUMNS view...
where column_name = 'ID'You need to think about this carefully. You might want different CACHE sizes or different INCREMENT BY clauses for certain tables. You might even (whisper it) want a sequence to be shared by more than one table.
Code generation is a useful technique, but it is a rare application where one case fits all.
Cheers, APC
Blog : http://radiofreetooting.blogspot.com/ -
Creating SYNONYM for all tables who don't have one at once!
Hello to all,
I'm trying to create synonyms for every table who's missing one at the moment. I'm trying this code:
declare
cursor cur_objects is
select obj.object_name , obj.owner
from all_objects obj
where owner = '&&SCHEMA_OWNER'
AND NOT EXISTS (SELECT *
FROM all_synonyms syn
WHERE obj.object_name = syn.table_name)
AND obj.object_type = 'TABLE'
AND obj.object_name LIKE 'CI_%';
begin
for rec_objects in cur_objects loop
begin
dbms_output.put_line(rec_objects.object_name);
execute immediate('create public synonym ' || rec_objects.object_name || ' for '
|| rec_objects.owner ||'.'||rec_objects.object_name )
exception when others then
null;
end;
end loop;
end;
I'm getting this error:
ORA-06550: line 10, column 37:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
begin function package pragma procedure subtype type use
<een ID>
<een scheidingsteken-ID tussen dubbele aanhalingstekens> form
current cursor
I'm still pretty new at PL/SQL and can't get it to work. Does anyone got any tips ?
Thnx alreadyOk now I got this error:
RA-06550: line 17, column 1:
PLS-00103: Encountered the symbol "EXCEPTION" when expecting one of the following:
* & = - + ; < / > at in is mod remainder not rem return
returning <een exponent (**)> <> or != or ~= >= <= <> and or
like LIKE2_ LIKE4_ LIKEC_ between into overlaps using ||
multiset bulk year DAY_ member SUBMULTISET_
The symbol ";" was substituted for "EXCEPTION" to continue. -
Creating synonys for all table
i want to create synonyms for all atbles.the synonyn name and table name are same.instead creating one by one synonym i wnat to create all synonyms at a time.
1)select 'CREATE PUBLIC SYNONYM'||' '||'test'||' '||'for' ||' '||'test' from dual
2)select OBJECT_NAME from user_objects where OBJECT_TYPE ='TABLE'
in the first query if we replace with test with 2nd query then we can get the script for that.
i replaced that biut its not working how to do itHere is a generic grant script. If you review it, you will see how it works and can adapt it to your varying needs.
BEGIN
FOR x IN ( SELECT owner,
object_name,
DECODE(object_type, 'TABLE' , 'select, insert, update, delete',
'SEQUENCE', 'select',
'VIEW', 'select',
'execute') AS privs,
DECODE (owner, 'SCHEMA_1', 'USER_1',
'SCHEMA_2', 'ROLE_A'
) AS app_user
FROM dba_objects
WHERE object_type IN ('TABLE', 'PACKAGE', 'PROCEDURE',
'FUNCTION', 'SEQUENCE', 'VIEW')
AND owner IN ('SCHEMA_1', 'SCHEMA_2' ))
LOOP
BEGIN
EXECUTE IMMEDIATE 'grant ' || x.privs || ' on ' || x.owner ||
'.' || x.object_name || ' to ' || x.app_user ;
EXECUTE IMMEDIATE 'create or replace synonym '|| x.app_user||'.'||x.object_name||
' for ' ||x.owner||'.'||x.object_name ;
EXCEPTION
WHEN others THEN
dbms_output.put_line('Bad owner = '||x.owner||'; Bad app_user='||x.app_user||
'; Bad object_name='||x.object_name);
END;
END LOOP;
END;
/ -
Hi Guru’s,
I have an issue in Transaction SE16, Field selection (User-Specific Settings) is NOT working in Tables (ALL tables).
Following is the screenshot attached for your kind reference,
That is in the initial screen of transaction SE16 if I choose Filed Name or Filed Label only the technical details (Field Names) are appearing and not the descriptions like Client, Purchasing Doc, and Company Code Doc. Category Document Type etc…
Right now I am using ECC6 and EHP7 SAP system.
Please help me to resolve this issue by implementing any OSS note or User Role creations or any technical changes required in system.
Hope the requirement is clear and in case need any clarification please revert back.
NOTE: Right now in Development System we don’t have any successful user to compare the settings.
Regards,
Kumar.SThanks Patra.
Even I searched in SAP portal and couldn't able to find the relevant OSS note.
Following is my BASIS team response,
"Only you can view Table Field values from higher release"
Can you suggest / guide on this comment as well.
Looking forward to your speedy response.
Regards,
Kumar.S -
Create user with read access for all tables SAP SID .*
Hello all,
could you please help me ? I would like to grant select privilege on all tables SAP<SID>.* for newly created user.
I have created standard database user (not exclusive).
I`m able to grant select for individual tables, but I would like to grant select for this user on all SAP<SID>
schema in simplier way
But as far as I know, the schema`s owner name must be different then schema name.
Any idea please ?
Thank you.
Pavolcreate user <user_name> identified by <password> <options>;
grant read on all tables:-
CREATE OR REPLACE PROCEDURE GRANT_SELECT AS
CURSOR ut_cur IS
SELECT table_name
FROM user_tables;
RetVal NUMBER;
sCursor INT;
sqlstr VARCHAR2(250);
BEGIN
FOR ut_rec IN user_tabs_cur;
LOOP
sqlstr := 'GRANT SELECT ON '|| ut_rec.table_name
|| ' TO <user_name>';
sCursor := dbms_sql.open_cursor;
dbms_sql.parse(sCursor,sqlstr, dbms_sql.native);
RetVal := dbms_sql.execute(sCursor);
dbms_sql.close_cursor(sCursor);
END LOOP;
END grant_select;
Edited by: varun4dba on Jan 18, 2011 4:13 PM
Maybe you are looking for
-
Updated Yoga 13 to Windows 8.1 - Now No Video or Audio in Installed Apps
I upgraded to WIndows 8.1 a few hours ago (available in Store). However, ever since the upgrade I can no longer watch videos or hear sound in all Apps. Netflix gives me a message that there is a problem with this system's configuration that prevents
-
Security erasure of sun hard disk drives
hi there, first of all i am an absolute beginner when it comes to sun systems so i do apologise if this is the wrong type of forum for me, my problem is i have several sun ULTRASPARC 60 CREATOR 3D tower systems and i need to erased the hard drives se
-
How do i set a background of the button as an image??
hey guys... i was wondering if there is a way i could change the background of spark button component to an image?? ive looked into the icon property of the spark button, but thats not what i need... i need the entire background of an image to be an
-
We use SAP Solution Manager 4.0, SPS 13 for System Monitoring of almost 100 systems. We configured SOLMAN as CEN system and activated the CCMSPING with push option. For almost the 2/3 of the systems we configured SAPCCM4X agents. Our current problem
-
I'm trying to build a vi that can send and receive data to a mySQL database (basically just timestamps and values). I have been able to do this using Microsoft's ODBC driver and the LabVIEW 8.2 DB Tools vi's, but the querying and writing seems to be