I have found methods to identify columns with duplicate values and I can use Select Distinct to find columns with only a single value, but I have a lot of tables with hundreds of columns and sometimes millions of rows. I need to find every column name where that column contains only 0, 0.00, Z, N, or Y. Essentially trying to create a list of useless columns.
How do I iterate select distinct (or something along those lines) across every column, one column at a time, and identify those instances in a table where the column values are the same in every row? Or alternatively, instances where the row count is less than 2.
This seems sort of close but specifying the value isn't going to help: SQL Server SELECT where any column contains 'x'
Group by and Having > 1 sort of works but I would have to run it for each column.
Select Distinct works but I have to run it one column at a time unless there is some better method I am missing.
I got a few of these methods to cooperate but only on numeric columns: Find columns that contain only zeros
This works to identify columns containing only NULL but I can't seem to get it do work for any other value:
DECLARE crs CURSOR LOCAL FAST_FORWARD FOR SELECT name FROM syscolumns WHERE id=OBJECT_ID('TABLENAME')
OPEN crs
DECLARE @name sysname
FETCH NEXT FROM crs INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC('SELECT ''' + @name + ''' WHERE NOT EXISTS (SELECT * FROM TABLENAME WHERE ' + @name + ' IS NOT NULL)')
FETCH NEXT FROM crs INTO @name
END
CLOSE crs
DEALLOCATE crs
I have started adapting a bit but am hitting errors about incorrect syntax near from:
DECLARE crs CURSOR LOCAL FAST_FORWARD FOR SELECT name FROM syscolumns WHERE id=OBJECT_ID('TABLENAME')
DECLARE @sql NVARCHAR(MAX)
OPEN crs
DECLARE @name sysname
FETCH NEXT FROM crs INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
Create Table #Temp (ID NVARCHAR, Info INT)
SET @sql = N'select distinct ''' + @name + ''' insert into #Temp (ID) from TABLENAME; SELECT COUNT(*) from #Temp Having COUNT(*)<2 insert into #Temp (Info);'
EXEC sp_executesql @sql
DROP TABLE #Temp
FETCH NEXT FROM crs INTO @name
END
CLOSE crs
DEALLOCATE crs