SQL - Query to get db/table names and update statistics

1k Views Asked by At

I have a query which generate 'Update Statistics' queries for me which I then run manually.

I do something like:

select concat('Update statistics ',Database_Name,'.dbo.Table') from Dbinfo..Tables

I would like to automate this using a job. What I have is:

declare @listdb as varchar(max)
set @listdb += @listdb (select concat('Update statistics ',Database_Name,'.dbo.Table') from Dbinfo..Tables)

Printing @listdb will return this result:

update statistics db1.dbo.Table;
update statistics db2.dbo.Table;
update statistics db3.dbo.Table;

The missing part is: How to I execute each generated line?

1

There are 1 best solutions below

5
Sean Lange On

You did the hard part which was creating the dynamic sql to run. All you need to do is execute the @listdb string like this.

exec sp_executesql @listdb