question

ACV24 avatar image
ACV24 asked

How to return the most common value for every column in every table in a DB

Is there a way to do this in SQL Server 2005? I was trying a cursor but i would need to return two variables into the cursor, the table name and the column name from system tables...any help would be great?
tables
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
ACV24 avatar image
ACV24 answered
I think i figured out a solution: -------------------------------------------------------------------- --checks if the temp table exists and re-creates it for each run ---------------------------------------------------------------------- if exists ( select * from tempdb.dbo.sysobjects o where o.xtype in ('U') and name LIKE '#columnCount%' ) DROP TABLE #columnCount GO create table #columnCount ( TableName varchar(100), ColumnName varchar(100), maxValue varchar(100), valueCount bigint ) GO --------------------------------------------------------------- --BEGIN CURSOR CODE to pull all tables and column names and put into temp table ---------------------------------------------------------------- DECLARE @tableName varchar(150) DECLARE @columnName varchar(150) DECLARE @sql varchar(max) DECLARE @metric cursor SET @metric = CURSOR FOR select a.name, b.name from sys.objects a JOIN sys.columns b on a.object_id = b.object_id WHERE a.type = 'U' and a.schema_id = 1 OPEN @metric FETCH NEXT FROM @metric INTO @tableName, @columnName WHILE @@FETCH_STATUS = 0 BEGIN SET @sql = ' INSERT INTO #columnCount (tableName, columnName, maxValue, valueCount) SELECT TOP 1 ''' +@tableName+ ''', ''' +@columnName+ ''', ' +@columnName+ ', count(*) as Count from ' +@tableName+ ' group by ' +@columnName+ ' order by count(*) desc ' EXEC (@sql) FETCH NEXT FROM @metric INTO @tableName, @columnName END CLOSE @metric DEALLOCATE @metric select * from #columnCount order by tableName, columnName
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.