Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>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. </p> <p><strong>Option 1 - a so/so method</strong> </p> <pre><code>SET NOCOUNT ON; DECLARE @Views as TABLE (Object_id int, name nvarchar(200)); INSERT INTO @Views (Object_ID, name) SELECT Object_ID, name FROM sys.views DECLARE @viewName nvarchar(200) = (select top 1 name from @Views); DECLARE @sql nvarchar(max) = ''; WHILE(Exists(select 1 from @Views)) BEGIN SET @sql = 'select count(*) FROM ' + @ViewName +';' --exec(@sql); --careful you're not accepting user input here! Print (@sql); DELETE FROM @Views where name = @viewName; SET @ViewName = (select top 1 name from @Views); END; </code></pre> <p><strong>Option 2 - A More Resilient Method</strong><br> <em>While trying this out in my little test DB I realized my first solution (as well as all the others) have a potential issue.</em> Views <em>can</em> 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.</p> <pre><code>SET NOCOUNT ON; DECLARE @ViewCount int = 0; DECLARE @Counter int = 0; DECLARE @sql nvarchar(max) = ''; DECLARE @viewName nvarchar(200) = '' DECLARE @Views as TABLE ( rownum int identity(1,1), name nvarchar(200), Primary Key clustered (rownum) ); INSERT INTO @Views (name) SELECT name FROM sys.views; SET @ViewCount = SCOPE_IDENTITY(); WHILE(@Counter &lt; @ViewCount) BEGIN SET @Counter = @Counter+1; SELECT @sql = 'select count(*) FROM ' + name +';', @viewName = name FROM @Views WHERE rownum = @Counter; BEGIN TRY -- exec(@sql); --careful you're not accepting user input here! Print (@sql); END TRY BEGIN CATCH Print ('ERROR querying view - ' + @viewname + ' // ' + ERROR_MESSAGE()); END CATCH END; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload