Hi @Zaran ,
Please try the following. Thanks!
CREATE TABLE test(Name1 VARCHAR(10),Name2 VARCHAR(10), Color VARCHAR(10), ID_Test VARCHAR(10))
INSERT INTO test VALUES
(' ',' ','Brown',' ')
,(' ',' ','Red','1')
,('Alice',' ',' ',' ')
,('Fred','Bron ',' ',' ')
,('Fred','Rose',' ','111')
,('Pop','Bin ',' ','10')
,('Blace','Bin ',' ','0')
DECLARE @ColumnTable TABLE (id INT IDENTITY, column_name VARCHAR(100))
DECLARE @DestinationTable TABLE (id INT IDENTITY, column_name VARCHAR(100), value1 INT, value2 DECIMAL(10,2))
INSERT INTO @ColumnTable (column_name)
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'test'
DECLARE @columnName VARCHAR(100)
DECLARE @id AS INT
DECLARE @sqlText VARCHAR(1000);
WHILE EXISTS (SELECT * FROM @ColumnTable)
BEGIN
SELECT TOP 1 @columnName = column_name, @id = id FROM @ColumnTable
SET @sqlText = 'SELECT '''+ @columnName + ''' AS column_name, COUNT(DISTINCT ' + @columnName + ' ) AS value1, CAST(SUM(CASE WHEN ' + @columnName +
' = NULL OR TRIM( '+ @columnName + ' ) = '''' THEN 1 ELSE 0 END) * 1.0 / COUNT(*) AS DECIMAL(10,2)) AS value2 FROM test'
INSERT INTO @DestinationTable
Exec (@sqlText)
DELETE FROM @ColumnTable WHERE id = @id
END
SELECT * FROM @DestinationTable