How to find out whether a table has some unique columns

前端 未结 5 2022
太阳男子
太阳男子 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条回答
  •  日久生厌
    2020-12-06 06:29

    A few words what my code does:

    1. Read's all tables and columns

    2. Creates a temp table to hold table/columns with duplicate keys

    3. For each table/column it runs a query. If it finds a count(*)>1 for at least one value it makes an insert into the temp table

    4. Select's column and values from the system tables that do not match table/columns that are found to have duplicates

      DECLARE @sql VARCHAR(max)
      DECLARE @table VARCHAR(100)
      DECLARE @column VARCHAR(100)
      
      
      CREATE TABLE #temp (tname VARCHAR(100),cname VARCHAR(100))
      
      DECLARE mycursor CURSOR FOR
      select t.name,c.name
      from sys.tables t
      join sys.columns c on t.object_id = c.object_id
      where system_type_id not in (34,35,99)
      
      OPEN mycursor
      FETCH NEXT FROM mycursor INTO @table,@column
      
      WHILE @@FETCH_STATUS = 0
      BEGIN
      SET @sql = 'INSERT INTO #temp SELECT DISTINCT '''+@table+''','''+@column+ ''' FROM ' + @table + ' GROUP BY ' + @column +' HAVING COUNT(*)>1 '
      EXEC (@sql)
      FETCH NEXT FROM mycursor INTO @table,@column
      END
      
      select t.name,c.name
      from sys.tables t
      join sys.columns c on t.object_id = c.object_id
      left join #temp on t.name = #temp.tname and c.name = #temp.cname
      where system_type_id not in (34,35,99) and #temp.tname IS NULL
      
      DROP TABLE #temp
      
      CLOSE mycursor
      DEALLOCATE mycursor
      

提交回复
热议问题