-5

I wrote this short script which finds a specific column name in a SQL Server database:

SELECT
    sys.columns.name AS ColumnName,
    tables.name AS TableName
FROM
    sys.columns
JOIN 
    sys.tables ON sys.columns.object_id = tables.object_id
WHERE
    sys.columns.name LIKE '%ColumnName%'

I want to add another resulting column where number of rows of each column.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sam Al-Ghammari
  • 1,021
  • 7
  • 23
  • @debugging XD Do you mean distinct values or number of rows? Because the number of rows per column per table is the number of rows of that table. – SNR Mar 14 '19 at 16:24
  • @SNR number of rows of that table – Sam Al-Ghammari Mar 14 '19 at 16:26
  • @SNR Given a single column name, he wants the script to report back which table has that column, and how many rows it has. (Edit: since he's using LIKE I guess he wants partial matches in the report too.) – Bampfer Mar 14 '19 at 16:26
  • @debuggingXD, Bampfer Thanks, it seems that sys.partitions view has the number of rows per partition. https://stackoverflow.com/questions/1443704/query-to-list-number-of-records-in-each-table-in-a-database – SNR Mar 14 '19 at 16:34
  • @SNR Ture, this is what I wanted in the resulting rows column. I tried this one, but it gives the column rows for all tables. I am just searching for a ColumnName then I need how many rows. – Sam Al-Ghammari Mar 14 '19 at 16:38

2 Answers2

0
SELECT
  sys.columns.name AS ColumnName,
  tables.name AS TableName, Totals.Total

FROM
  sys.columns
JOIN sys.tables ON
  sys.columns.object_id = tables.object_id 
  JOIN
    (SELECT COUNT(*) total, sys.columns.name FROM
  sys.columns
JOIN sys.tables ON
  sys.columns.object_id = tables.object_id
  GROUP BY sys.columns.name
    ) Totals
    on Totals.name = sys.columns.name
WHERE
  sys.columns.name LIKE '%ColumnName%'

This returns the number of times a column exists across all of the tables

Schmocken
  • 603
  • 8
  • 15
0

Assuming that there aren't any partitioned table:

USE [SpecificDatabank]
SELECT
  sys.columns.name AS ColumnName,
  sys.tables.name AS TableName,
  sys.partitions.rows AS [Rows]
FROM
  sys.columns
JOIN sys.tables ON
  sys.columns.object_id = sys.tables.object_id
JOIN sys.partitions ON
  sys.tables.object_id = sys.partitions.object_id and sys.partitions.index_id in (0,1)
WHERE
  sys.columns.name LIKE '%ColumnName%'
SNR
  • 712
  • 1
  • 8
  • 22
  • 1
    Note that sys.partitions.rows is approximate. But for many purposes this would be close enough. – Bampfer Mar 14 '19 at 16:42