[dba-SQLServer] Adding a field to all user tables

Robert Stewart rls at WeBeDb.com
Fri Jan 27 11:54:42 CST 2012


For whatever reason, my original post of this never seems to appear 
on the results from the list.

While I do not advocate using cursors 99% of the time, there are 
times that they are what you should use.
This will make the code easier to read, and it will work smooth.

CREATE PROCEDURE dbo.usp_AddTimestamp
AS
BEGIN
     SET NOCOUNT ON;
     DECLARE
             @TableName VARCHAR( 128 )
           , @Sql NVARCHAR( 4000 )

     DECLARE curTableList CURSOR
         FOR SELECT name
               FROM sysobjects
               WHERE [TYPE] = 'U'
               ORDER BY name

     OPEN curTableList

     FETCH next FROM curTableList INTO @TableName

     WHILE @@FETCH_STATUS = 0
         BEGIN
             SET @Sql = N'ALTER TABLE dbo.' + @TableName + ' ADD Timestamp'

             EXEC sp_executesql @Sql

             FETCH next FROM curTableList INTO @TableName
         END

     CLOSE curTableList
     DEALLOCATE curTableList
END
GO


More information about the dba-SQLServer mailing list