get a count of each value from every column in a table SQL Server

前端 未结 3 1874
庸人自扰
庸人自扰 2021-01-14 20:20

So I looked this up and this question is very similar but it\'s missing a key piece: SQL Server count number of distinct values in each column of a table

So in that

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-14 20:41

    thought i would take a stab at this whilst waiting for a backup to restore

    hope this does what you require

    create Table #Temp 
    (tableName varchar(100),
    columnName varchar(100),
    value varchar(1000),
    distinctItems int)
    
    Declare @tabName as varchar(100)
    Declare @colName as varchar(100)
    Declare @tabid as int
    
    Declare cursorTables Cursor
    for 
    select t.object_id , t.name , c.name from sys.tables t inner join sys.columns c on     t.object_id = c.object_id
    
    open cursorTables 
    Fetch Next from cursorTables into 
    @tabid,@tabName,@colName
    
    
    while @@Fetch_Status = 0 
    Begin
    
    declare @query as nVarchar(1000)
    set @query  = 'Insert into #Temp SELECT    ''' + @tabName + '''  , '''+ @colName +''', '     + @colName + ',  COUNT([' + @colName +']) AS Expr1 FROM          [' + @tabName+ '] group by     [' + @colName + ']'
    print @query
    exec sp_executesql @query
    
    Fetch Next from cursorTables into 
    @tabid,@tabName,@colName
    
    
    End 
    
    Close cursorTables
    Deallocate cursorTables
    
    select * from #temp
    
    drop table #temp
    

    produces some not very useful results on PK values and i suspect it would not work on columns greater than varchar(1000) but works on a fe of my dbs

提交回复
热议问题