Chris Skorlinski Microsoft SQL Server Escalation Services
Not very fancy, but here are some examples of executing same statement for multiple tables in a database. The first two techniques build a TSQL statement in the query output window. You can then copy-n-paste that text into a new query and execute. The last two examples just execute the statement by substituting the table name for the ‘?’.
--Build a TSQL Statement for all user tables in a database.
select 'select count(*) from SalesLT.' + name + CHAR(13) + CHAR(10) + 'go' + CHAR(13) + CHAR(10) from sys.sysobjects where type = 'U'
--Sample Output: --Copy-n-Paste output to new Query
select count(*) from SalesLT.Address go select count(*) from SalesLT.Customer go select count(*) from SalesLT.CustomerAddress go select count(*) from SalesLT.Product go
--Build a TSQL Statement for all user tables in a database. select 'exec(' + '''select count(*) from SalesLT.' + name + ''')' from sys.sysobjects where type = 'U'
--Sample Output: --Copy-n-Paste output to new Query exec('select count(*) from SalesLT.Address') exec('select count(*) from SalesLT.Customer') exec('select count(*) from SalesLT.CustomerAddress') exec('select count(*) from SalesLT.Product')
--Executes statements below for each table in the database EXEC sp_MSforeachtable 'UPDATE STATISTICS ? WITH FULLSCAN' EXEC sp_MSforeachtable "SELECT count(*) from ?"