Question
How do i loop though my list of views in my SQL DB?
background and things tried
I have googled around for about 2 hours now and i have found quite a few ways to loop through different attributes of my DB. I can loop through a list of tables and a list of columns and a list of counts but i have yet to find anything that allows me to loop through a list of Views.
code to loop through tables i tried to modify
link i used to obtain sample code below
--List all the tables of current database and total no rows in it
EXEC sp_MSForEachTable 'SELECT ''?'' as TableName, COUNT(1)
as TotalRows FROM ? WITH(NOLOCK)'
--List all the tables of current database and space used by it EXECUTE sp_MSforeachtable 'EXECUTE sp_spaceused [?];';
GO
sudo code for what i want to do
loop through each view in list
run query here for each view
output results
request for help
Can anyone link me to more information about how to do this or provide some sample code? All help is greatly appreciated! Thanks!
There are a lot of ways to do this, cursors, manual loops. There are likely ways to find what you want (meaning the answer to your mystery query) in a set based way. Either way, as phrased you’ll need dynamic sql.
Option 1 – a so/so method
Option 2 – A More Resilient Method
While trying this out in my little test DB I realized my first solution (as well as all the others) have a potential issue. Views can become out of date –meaning underlying objects change like a column rename. All of the others solutions will throw an error and stop processing. If you’re doing large/long queries this may be undesirable. So I added a smidge of error handling to note the error and continue on processing.