Records not shown while selecting from table in mssql - sql

I'm Getting total tables in whole database and its row-count from following query:
SELECT SCHEMA_NAME(A.schema_id) + '.' +
A.Name, SUM(B.rows) AS 'RowCount'
FROM sys.objects A
INNER JOIN sys.partitions B ON A.object_id = B.object_id
WHERE A.type = 'U'
GROUP BY A.schema_id, A.Name
Order By 'RowCount' desc
After that i'm getting below result:
And then finally when i'm trying to fetch records from one of this table
select * from dbo.[xxx_$Retail ICT Header]
It gives 0 rows as output......Any clue?

To get the Row count in each table try below query and after that cross check by running select query.
SELECT s.name+'.'+o.name,
ddps.row_count
FROM sys.indexes AS i
INNER JOIN sys.objects AS o ON i.OBJECT_ID = o.OBJECT_ID
INNER JOIN sys.schemas s on s.schema_id= o.schema_id
INNER JOIN sys.dm_db_partition_stats AS ddps ON i.OBJECT_ID = ddps.OBJECT_ID
AND i.index_id = ddps.index_id
WHERE i.index_id < 2 AND o.is_ms_shipped = 0 ORDER BY o.NAME

Related

SQL: count and show all rows and columns of all tables under a scheme

somewhere on the net (source missing, may be here) I got this SQL-statement:
SELECT t.NAME AS TableName, SUM(a.total_pages) * 8 AS TotalSpaceKB, p.Rows FROM sys.tables t
INNER JOIN sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE t.NAME NOT LIKE 'dt%' AND t.NAME LIKE '%MY_TABLES%' AND s.Name LIKE 'MY_ACHEMA'
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY t.Name, p.Rows
ORDER BY p.Rows DESC
which gives me a beautiful view with 3 columns. something like this:
TableName TotalSpaceKB Rows
TABLE 3231656 76000
TABLE 2305632 29136
TABLE 2213128 14160
TABLE 1954200 3020
etc...
now I'd like to expand it to inclide the number of columns of each table. How can this be done?
I removed the grouping and used subqueries:
SELECT
t.NAME AS TableName,
(SELECT SUM(a.total_pages) * 8
FROM sys.indexes i
INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN sys.allocation_units a ON p.partition_id = a.container_id
WHERE t.OBJECT_ID = i.object_id AND i.OBJECT_ID > 255
) AS TotalSpaceKB,
(SELECT SUM(p.Rows)
FROM sys.indexes i
INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
WHERE t.OBJECT_ID = i.object_id AND i.OBJECT_ID > 255
) AS Rows,
(SELECT COUNT(*) FROM sys.columns c WHERE t.OBJECT_ID = c.object_id) AS Columns
FROM sys.tables t
LEFT OUTER JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE t.NAME NOT LIKE 'dt%' AND t.NAME LIKE '%MY_TABLES%' AND s.Name LIKE 'MY_ACHEMA'
AND t.is_ms_shipped = 0
ORDER BY Rows DESC
This should work for you by adding in the INFORMATION_SCHEMA.COLUMNS.
SELECT t.NAME AS TableName, SUM(a.total_pages) * 8 AS TotalSpaceKB, p.Rows, COUNT(COLUMN_NAME) AS ColumnCount
FROM sys.tables t
INNER JOIN sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN sys.allocation_units a ON p.partition_id = a.container_id
LEFT JOIN sys.schemas s ON t.schema_id = s.schema_id
LEFT JOIN INFORMATION_SCHEMA.COLUMNS ISC ON t.NAME = ISC.TABLE_NAME
WHERE t.NAME NOT LIKE 'dt%' AND t.NAME LIKE '%MY_TABLES%' AND s.Name LIKE 'MY_ACHEMA'
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY t.Name, p.Rows
ORDER BY p.Rows DESC

Getting duplication with inner join and left join

I am trying to fetch following information for the table of the columns :
1) Primary key.
2) IsNullable
3) Is_Identity.
Query :
SELECT c.name 'Column Name',c.is_nullable,c.is_identity,ISNULL(i.is_primary_key, 0) 'Primary Key' FROM sys.columns c INNER JOIN sys.types t ON c.user_type_id = t.user_type_id LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id WHERE c.object_id = OBJECT_ID('[HumanResources].[Employee]')
I am working with Adventure Works database but the problem here is I am getting OrganizationNode column 2 times and I am unable to understand the reason.
For other tables I am not getting this issue but I am only getting this problem for the table [HumanResources].[Employee].
Below is the link to download database bak file :
https://www.dropbox.com/s/nutfat17b73boav/AdvantureWorksSeScript.bak?dl=0
I have also tried distinct but because of that it shuffled up the ordering of the column as you can see in the second output. BirthDate is coming at the top instead of BusinessEntityID.
I would not like to use distinct as my below query is working fine with all other tables but I am not getting why it is giving duplicate columns in case of [HumanResources].[Employee] table or may be I have tested it with few tables and query may not work properly for few other databases.
I am not sure whether my query is correct or not to work in all the scenarios to fetch above 3 things(pk,inullable etc.) which I mention.
Try this
SELECT name,
is_identity,
is_nullable,
is_primary_key
FROM (
SELECT c.name,
c.column_id,
c.is_identity,
c.is_nullable,
ISNULL(i.is_primary_key,0) is_primary_key,
ROW_NUMBER() OVER(PARTITION BY c.name ORDER BY c.name) rn
FROM sys.columns c
JOIN sys.tables t
ON t.object_id = c.object_id
LEFT JOIN sys.index_columns ic
ON c.object_id = ic.object_id AND c.column_id = ic.column_id
LEFT JOIN sys.indexes i
ON i.object_id = ic.object_id AND i.index_id = ic.index_id
WHERE t.name = 'Employee'
)keys
WHERE rn = 1
ORDER BY column_id

Most updated and deleted table?

How can we see most deleted and most updated table in sql server 2012 and upper levels.
And how can we see table that makes the most io?
Does these statistics withheld in Sql Server?
Index fragmentation should help - looking at number of rows and fragmentation:
SELECT
B.name AS TableName
,C.name AS IndexName
,C.fill_factor AS IndexFillFactor
,D.rows AS RowsCount
,A.avg_fragmentation_in_percent
,A.page_count
FROM
sys.dm_db_index_physical_stats(DB_ID(),NULL,NULL,NULL,NULL) A
INNER JOIN
sys.objects B
ON
A.object_id = B.object_id
INNER JOIN
sys.indexes C
ON
B.object_id = C.object_id AND A.index_id = C.index_id
INNER JOIN
sys.partitions D
ON
B.object_id = D.object_id AND A.index_id = D.index_id
WHERE
C.index_id > 0
order by
avg_fragmentation_in_percent desc
PFE: Thanks to Neeraj Dwivedi at SQL Central

Can I find which indexes are current / in use

I have the following:
SELECT name AS index_name,
STATS_DATE(OBJECT_ID, index_id) AS StatsUpdated
FROM sys.indexes
Is it possible to add some information so I have an idea if each index is current and in use?
Also I'd like to return in the SELECT clause which table the index is on?
I am using the following query to find if an index is is use - if seeks,scans and look-ups are zero then it's not used.
SELECT TOP 25
o.name AS ObjectName
, i.name AS IndexName
, i.index_id AS IndexID
, dm_ius.user_seeks AS UserSeek
, dm_ius.user_scans AS UserScans
, dm_ius.user_lookups AS UserLookups
, dm_ius.user_updates AS UserUpdates
, p.TableRows
, is_disabled
,STATS_DATE(i.[OBJECT_ID], i.index_id) AS StatsUpdated
FROM sys.dm_db_index_usage_stats dm_ius
INNER JOIN sys.indexes i ON i.index_id = dm_ius.index_id AND dm_ius.object_id = i.object_id
INNER JOIN sys.objects o on dm_ius.object_id = o.object_id
INNER JOIN sys.schemas s on o.schema_id = s.schema_id
INNER JOIN (SELECT SUM(p.rows) TableRows, p.index_id, p.object_id
FROM sys.partitions p GROUP BY p.index_id, p.object_id) p
ON p.index_id = dm_ius.index_id AND dm_ius.object_id = p.object_id
WHERE OBJECTPROPERTY(dm_ius.object_id,'IsUserTable') = 1
AND dm_ius.database_id = DB_ID()
AND i.type_desc = 'nonclustered'
AND i.is_primary_key = 0
AND i.is_unique_constraint = 0
ORDER BY (dm_ius.user_seeks + dm_ius.user_scans + dm_ius.user_lookups) ASC
GO

Script that provides the row counts and table names

Maybe you easily said how to I provide table names and row counts?
Pseudo SQL:
for "select tablename from system.Tables" into :tablename
execute "select count(*) from ? into ?" using :tablename, :count
return row(:tablename, :count)
end for
Can you tell me show me this script in T-SQL?
If you're on SQL Server 2005 or newer (you unfortunately didn't specify which version of SQL Server you're using), this query should give you that information:
SELECT
TableName = t.NAME,
TableSchema = s.Name,
RowCounts = p.rows
FROM
sys.tables t
INNER JOIN
sys.schemas s ON t.schema_id = s.schema_id
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
WHERE
t.is_ms_shipped = 0
GROUP BY
t.NAME, s.Name, p.Rows
ORDER BY
s.Name, t.Name
This produces an output something like (this is from AdventureWorks):
TableName TableSchema RowCounts
AWBuildVersion dbo 1
DatabaseLog dbo 1597
ErrorLog dbo 0
Department HumanResources 16
Employee HumanResources 290
JobCandidate HumanResources 13
Address Person 19614
AddressType Person 6
... and so on......
SELECT
t.NAME AS TableName, p.[Rows] FROM
sys.tables t INNER JOIN
sys.partitions p ON t.object_id = p.OBJECT_ID GROUP BY
t.NAME, p.[Rows] ORDER BY t.NAME
-- Shows all user tables and row counts for the current database
-- Remove OBJECTPROPERTY function call to include system objects
SELECT o.NAME,
i.rowcnt
FROM sysindexes AS i
INNER JOIN sysobjects AS o ON i.id = o.id
WHERE i.indid < 2 AND OBJECTPROPERTY(o.id, 'IsMSShipped') = 0
ORDER BY o.NAME
exec sp_MSForEachTable 'SELECT ''?'' as TableName, COUNT(*) as Rows FROM ?'
I have adjusted the answer from marc_c with CTE and displaying it with choice of displaying just the schema you are after.
Should work with SQL Serve 2005 and newer.
WITH CountRowsInTables (Table_Name, Table_Schema, Row_Counts) AS
(
SELECT
TableName = t.Name,
TableSchema = s.Name,
RowCounts = p.Rows
FROM
sys.tables t
INNER JOIN
sys.schemas s ON t.schema_id = s.schema_id
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
WHERE
t.is_ms_shipped = 0
GROUP BY
s.Name, t.Name, p.Rows
)
SELECT Table_name, Table_Schema, Row_Counts
FROM CountRowsInTables
WHERE Table_Schema = 'Pick_Schema_to_display';
Try this
-- drop table #tmpspace
create table #tmpspace (
name sysname
, rows int
, reserved varchar(50)
, data varchar(50)
, index_size varchar(50)
, unused varchar(50)
)
dbcc updateusage(0) with NO_INFOMSGS
exec sp_msforeachtable 'insert #tmpspace exec sp_spaceused ''?'''
select * from #tmpspace
order by convert(int, substring(reserved, 1, charindex(' ', reserved))) desc, rows desc, name
Works on sql2000 too.
dbcc updateusage might take some time but results will be 100% actual. Skip it if you need speed over accuracy.
This works for me:
SELECT sc.name +'.'+ ta.name TableName
,SUM(pa.rows) RowCnt
FROM sys.tables ta
INNER JOIN sys.partitions pa
ON pa.OBJECT_ID = ta.OBJECT_ID
INNER JOIN sys.schemas sc
ON ta.schema_id = sc.schema_id
WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
GROUP BY sc.name,ta.name
ORDER BY SUM(pa.rows) DESC