Skip to content

Instantly share code, notes, and snippets.

@DylanKnevitt
Last active December 18, 2015 02:58
Show Gist options
  • Save DylanKnevitt/5714447 to your computer and use it in GitHub Desktop.
Save DylanKnevitt/5714447 to your computer and use it in GitHub Desktop.
A loop to select all tables and views in a database. I will add more to this, such as executing stored procedures, doing inserts, updates, deletes and whatever other operations I can think of, as time goes on. This is all to test every object in your database with the Tuning advisor.
DECLARE TOCURSOR CURSOR FOR
SELECT('SELECT * FROM ' + name + ';')
FROM sys.tables
UNION ALL
SELECT('SELECT * FROM ' + name + ';')
FROM sys.views
DECLARE @query NVARCHAR(MAX)
OPEN TOCURSOR
FETCH NEXT FROM TOCURSOR INTO
@query
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC (@query)
FETCH NEXT FROM TOCURSOR INTO
@query
END
CLOSE TOCURSOR
DEALLOCATE TOCURSOR
@DylanKnevitt
Copy link
Author

Not only has this helped me speed up my database, it also helped me find some old views that don't work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment