Advertisement
Guest User

DanSpd

a guest
Mar 2nd, 2010
914
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 1.57 KB | None | 0 0
  1. USE World00_Character
  2. GO
  3.  
  4. -- Create a cursor to loop through the System Ojects and get each table name
  5. DECLARE TBL_CURSOR CURSOR
  6. -- Declare the SQL Statement to cursor through
  7. FOR ( SELECT Name FROM Sysobjects WHERE TYPE='U' )
  8.  
  9. -- Declare the @SQL Variable which will hold our dynamic sql
  10. DECLARE @SQL NVARCHAR(MAX);
  11. SET @SQL = '';
  12. -- Declare the @TblName Variable which will hold the name of the current table
  13. DECLARE @TblName NVARCHAR(MAX);
  14.  
  15. -- Open the Cursor
  16. OPEN TBL_CURSOR
  17.  
  18. -- Setup the Fetch While that will loop through our cursor and set @TblName
  19. FETCH NEXT FROM TBL_CURSOR INTO @TblName
  20. -- Do this while we are not at the end of the record set
  21. WHILE (@@FETCH_STATUS <> -1)
  22. BEGIN
  23. -- Appeand this table's select count statement to our sql variable
  24. SET @SQL = @SQL + ' ( SELECT '''+@TblName+''' AS Table_Name,COUNT(*) AS Count FROM '+@TblName+' ) UNION';
  25.  
  26. -- Delete info
  27. EXEC('DBCC CHECKIDENT ('+@TblName+',RESEED,(SELECT IDENT_SEED('+@TblName+')))');
  28.  
  29. -- Pull the next record
  30. FETCH NEXT FROM TBL_CURSOR INTO @TblName
  31. -- End the Cursor Loop
  32. END
  33.  
  34. -- Close and Clean Up the Cursor
  35. CLOSE TBL_CURSOR
  36. DEALLOCATE TBL_CURSOR
  37.  
  38. -- Since we were adding the UNION at the end of each part, the last query will have
  39. -- an extra UNION. Lets  trim it off.
  40. SET @SQL = LEFT(@SQL,LEN(@SQL)-6);
  41.  
  42. -- Lets do an Order By. You can pick between Count and Table Name by picking which
  43. -- line to execute below.
  44. SET @SQL = @SQL + ' ORDER BY Count';
  45. --SET @SQL = @SQL + ' ORDER BY Table_Name';
  46.  
  47. -- Now that our Dynamic SQL statement is ready, lets execute it.
  48. EXEC (@SQL);
  49. GO
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement