How to find out whether a table has some unique columns

前端 未结 5 2027
太阳男子
太阳男子 2020-12-06 06:25

I use MS SQL Server.

Ive been handed some large tables with no constrains on them, no keys no nothing.

I know some of the columns have unique values. Is ther

5条回答
  •  旧时难觅i
    2020-12-06 06:43

    Here is I think probably the cleanest way. Just use dynamic sql and a single select statement to create a query that gives you a total row count and a count of distinct values for each field.

    Fill in the DB name and tablename at the top. The DB name part is really important since OBJECT_NAME only works in the current database context.

    use DatabaseName
    
    DECLARE @Table varchar(100) = 'TableName'
    
    DECLARE @SQL Varchar(max)
    
    SET @SQL = 'SELECT COUNT(*) as ''Total'''
    
    SELECT @SQL = @SQL + ',COUNT(DISTINCT ' + name + ') as ''' + name + ''''
    FROM sys.columns c
    WHERE OBJECT_NAME(object_id) = @Table
    
    SET @SQL = @SQL + ' FROM ' + @Table
    
    exec @sql
    

提交回复
热议问题