Update table statistics dynamically across an entire SQL Server database

As in Oracle there is a table where all tables in the database (dba_tables) are listed and we can use it to perform maintenance operations dynamically, in Sql Server we can do the same by consulting the table [database].dbo.Sysobjects.

In the example below (as in others I've posted) I update the statistics of all tables in a Sql Server database dynamically by querying the data dictionary. This could be encapsulated in a stored procedure or directly executed in a job of the Agent of Sql Server to keep updated the statistics of all the tables of a database automatically.

-- Variables declaration
    DECLARE @dbName    sysname
    DECLARE @sample int
    DECLARE @SQL nvarchar(4000)
    DECLARE @ID int
    DECLARE @Tabla sysname
    DECLARE @RowCnt int

    -- Database filter and percent for statistics calculation
    SET @dbName = 'AdventureWorks2008'
    SET @sample = 100

    --Temp table
    CREATE TABLE ##Tablas
    (
     TableID INT IDENTITY(1, 1) NOT NULL,
     TableName SYSNAME NOT NULL
    )

    --Feed the table with a list of tables
    SET @SQL = ''
    SET @SQL = @SQL + 'INSERT INTO ##Tablas (TableName) '
    SET @SQL = @SQL + 'SELECT [name] FROM ' + @dbName + '.dbo.sysobjects WHERE xtype = ''U'' AND [name] <> ''dtproperties'''

    EXEC sp_executesql @statement = @SQL

    SELECT TOP 1 @ID = TableID, @Tabla = TableName
    FROM ##Tablas
    ORDER BY TableID

    SET @RowCnt = @@ROWCOUNT
   
    --For each table
    WHILE @RowCnt <> 0
    BEGIN

     SET @SQL = 'UPDATE STATISTICS ' + @dbname + '.dbo.[' + @Tabla + '] WITH SAMPLE ' + CONVERT(varchar(3), @sample) + ' PERCENT'

     EXEC sp_executesql @statement = @SQL

     SELECT TOP 1 @ID = TableID, @Tabla = TableName
     FROM ##Tablas
     WHERE TableID > @ID
     ORDER BY TableID

     SET @RowCnt = @@ROWCOUNT

    END

--Drop the table
DROP TABLE ##Tablas