Selecting Rowcount and number of columns with one sql query? - sql

How can i club both the select count and select columns with one statement?

If you are just looking to see what "shape" your tables are in, something like this would work. But if you're wanting to know column/row counts for a given query, it may be possible but I don't know how to do it
; WITH ROW_COUNTS AS
(
SELECT
s.[Name] as [SchemaName]
, t.[name] as [TableName]
, SUM(p.rows) as [RowCounts]
FROM
sys.schemas s
LEFT JOIN
sys.tables t
ON s.schema_id = t.schema_id
LEFT JOIN
sys.partitions p
ON t.object_id = p.object_id
LEFT JOIN
sys.allocation_units a
ON p.partition_id = a.container_id
WHERE
p.index_id in(0,1) -- 0 heap table , 1 table with clustered index
AND p.rows is not null
AND a.type = 1 -- row-data only , not LOB
GROUP BY
s.[Name]
, t.[name]
)
, COLUMN_COUNTS AS
(
SELECT
s.[Name] as [SchemaName]
, t.[name] as [TableName]
, COUNT(c.column_id) as [ColumnCounts]
FROM
sys.schemas s
INNER JOIN
sys.tables t
ON s.schema_id = t.schema_id
INNER JOIN
sys.columns c
ON C.object_id = T.object_id
GROUP BY
s.[Name]
, t.[name]
)
SELECT
CC.SchemaName
, CC.TableName
, RC.RowCounts
, CC.ColumnCounts
FROM
COLUMN_COUNTS CC
INNER JOIN
ROW_COUNTS RC
ON RC.SchemaName = CC.SchemaName
AND RC.TableName = CC.TableName
ORDER BY
1,2
Results run against master
SchemaName TableName RowCounts ColumnCounts
dbo Hold_Cluster_Status 0 10
dbo MSreplication_options 3 6
dbo spt_fallback_db 0 8
dbo spt_fallback_dev 0 10
dbo spt_fallback_usg 0 9
dbo spt_monitor 1 11
dbo spt_values 2506 6

Using a COUNT() window aggregate you should be able to accomplish what you are looking to do. However, the DISTINCT against a very large table is not likely to be very performant:
SELECT DISTINCT a, b, c, COUNT(*) OVER (PARTITION BY 1) FROM <tablename>;
Another option would be but you are touching the table twice:
SELECT a,b,c, MyCount
FROM <tablename>
CROSS JOIN
(SELECT COUNT(*) AS MyCount
FROM <tablename>
)

I'm not 100% ure what you want, but here is a possible example...
SELECT
a,
b,
c,
(SELECT COUNT(*) FROM yourTable) as table_count
FROM
yourTable

Related

SqlServer - Get all tables that has data ( are not empty )

The question is simple:
Is it possible to retrive all the tables that are not empty ?
I need a query to list the tables. Is there a way ?
Thanks to support
Try this Script To get all tables with non empty records
USE [Your database Name]
Go
SELECT SCHEMA_NAME(schema_id) AS [SchemaName],
[Tables].name AS [TableName]
--SUM([Partitions].[rows]) AS [TotalRowCount]
FROM sys.tables AS [Tables]
JOIN sys.partitions AS [Partitions]
ON [Tables].[object_id] = [Partitions].[object_id]
AND [Partitions].index_id IN ( 0, 1 )
-- WHERE [Tables].name = N'name of the table'
GROUP BY SCHEMA_NAME(schema_id), [Tables].name
HAVING SUM([Partitions].[rows]) >0
Slightly different than #Sreenu131 answer as it is using sys.partitions .rows property to find
p.rows > 0
SELECT
sch.name as SchemaName,
t.NAME AS TableName,
p.rows AS RowCounts
FROM
sys.tables t
INNER JOIN
sys.partitions p ON t.object_id = p.OBJECT_ID
INNER JOIN sys.schemas sch
on t.schema_id = sch.schema_id
WHERE
t.NAME NOT LIKE 'dt%'
AND t.is_ms_shipped = 0
AND p.rows > 0
GROUP BY
sch.name,t.Name, p.Rows
ORDER BY
sch.name,t.Name

How to get the all table(s) name which are used in particular stored procedure?

I have a requirement to get all the database tables name which are used in specific stored procedure?
As an example, I have one stored procedure as given below.
CREATE PROCEDURE [dbo].[my_sp_Name]
#ID INT = NULL
AS
BEGIN
SELECT ID, NAME, PRICE
FROM tbl1
INNER JOIN tbl2 ON tbl1.ProductId = tbl2.ProductId
LEFT JOIN tbl3 ON tbl2.ProductSalesDate = tbl3.ProductSalesDate
LEFT JOIN tbl4 ON tbl1.ProductCode = tbl4.ItemCode
END
Expected output:
Used_Table_Name
tbl1
tbl2
tbl3
tbl4
Can any one suggest a way?
Below query will help you to get used database tables in stored procedure.
;WITH stored_procedures AS (
SELECT oo.name AS table_name,
ROW_NUMBER() OVER(partition by o.name,oo.name ORDER BY o.name,oo.name) AS row
FROM sysdepends d
INNER JOIN sysobjects o ON o.id=d.id
INNER JOIN sysobjects oo ON oo.id=d.depid
WHERE o.xtype = 'P' AND o.name = 'my_sp_Name'
)
SELECT Table_name AS 'Used_Table_Name' FROM stored_procedures
WHERE row = 1
Use below script to get table names in your store procedure :
SELECT DISTINCT [object_name] = SCHEMA_NAME(o.[schema_id]) + '.' + o.name
, o.type_desc
FROM sys.dm_sql_referenced_entities ('[dbo].[Your_procedurename]',
'OBJECT')d
JOIN sys.objects o ON d.referenced_id = o.[object_id]
WHERE o.[type] IN ('U', 'V')

Records not shown while selecting from table in mssql

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

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

How to find duplicate records in SQL?

I am trying to develop a query to insert unique records but am receiving the SQL Server Primary Key error for trying to insert duplicate records. I was able to insert some values with this query but not for this record (score_14).
So now I am trying to find duplicate record with the following query. The challenge is that my PK is based on 3 columns: StudentID, MeasureDate, and MeasureID--all from a different table not mentioned below.
But this only shows me count--instead I want to just return records with count > 1. How do I do that?
select count(a.score_14) as score_count, A.studentid, A.measuredate, B.measurename+' ' +B.LabelName
from [J5C_Measures_Sys] A
join [J5C_ListBoxMeasures_Sys] B on A.MeasureID = B.MeasureID
join sysobjects so on so.name = 'J5C_Measures_Sys'
join syscolumns sc on so.id = sc.id
join [J5C_MeasureNamesV2_Sys] v on v.Score_field_id = sc.name
where so.type = 'u' and sc.name = 'score_14' and a.score_14 is not null
AND A.STUDENTID IS NOT NULL AND A.MEASUREDATE IS NOT NULL AND B.MEASURENAME IS NOT NULL
--and count(a.score_14)>1
group by a.studentid, a.measuredate, B.measurename, B.LabelName, A.score_14
having count(a.score_14) > 1
Beth is correct - here's my re-write of your query:
SELECT a.studentid, a.measuredate, a.measureid
from [J5C_Measures_Sys] A
GROUP BY a.studentid, a.measuredate, a.measureid
HAVING COUNT(*) > 1
Previously:
SELECT a.studentid, a.measuredate, a.measureid
from [J5C_Measures_Sys] A
join [J5C_ListBoxMeasures_Sys] B on A.MeasureID = B.MeasureID
join sysobjects so on so.name = 'J5C_Measures_Sys'
AND so.type = 'u'
join syscolumns sc on so.id = sc.id
and sc.name = 'score_14'
join [J5C_MeasureNamesV2_Sys] v on v.Score_field_id = sc.name
where a.score_14 is not null
AND B.MEASURENAME IS NOT NULL
GROUP BY a.studentid, a.measuredate, a.measureid
HAVING COUNT(*) > 1
you need to take A.score_14 out of your group by clause if you want to count it