Insert CreatedBy and CreatedOn in Any Missing Data Tables in SQL

When we design Access with SQL Server solutions we almost always add CreatedBy and CreatedOn to all of our tables, allowing our clients to see who created records in the Access frontend.

Script to add CreatedBy and CreatedOn Automatically to tables

Many times we inherit SQL databases and we need a quick way to add both fields to all tables in the database. To that end we use the following script will check if CreatedBy and CreatedOn are present in the table and if they are not, add them:
DECLARE @ROWID Int
DECLARE @SQLExecute Varchar(max)
DECLARE @Table_Name VARCHAR(Max)
DECLARE @Qty Int
SET @rowid = 0
SET @Table_Name = ''
DECLARE grant_tbl_cursor CURSOR FOR
SELECT  Table_Name
FROM tblTablePermissions
OPEN grant_tbl_cursor
FETCH NEXT FROM grant_tbl_cursor
INTO @Table_Name
WHILE @@FETCH_STATUS = 0
BEGIN
IF COL_LENGTH(@Table_Name, 'CreatedOn') IS NULL
BEGIN
/*Column does not exist or caller does not have permission to view the object*/
select @sqlExecute = 'alter table [' + @Table_Name + '] add CreatedOn DateTime2(0) DEFAULT CURRENT_TIMESTAMP NULL' 
PRINT @SQLExecute
EXECUTE( @sqlExecute)
END
IF COL_LENGTH(@Table_Name, 'CreatedBy') IS NULL
BEGIN
select @sqlExecute = 'alter table [' + @Table_Name + '] add CreatedBy Varchar(25) DEFAULT suser_sname() NULL' 
EXECUTE( @sqlExecute)
End
FETCH NEXT FROM grant_tbl_cursor
INTO @Table_Name
END
CLOSE grant_tbl_cursor
DEALLOCATE grant_tbl_cursor

The script is reading from tblTablePermissions which is just a list of SQL Server tables used by the application. We use the table in our DSNless technique.

Once you have executed the script SQL Server will automatically date stamp and place the user’s network name in the CreatedBy field, allowing you to create analysis on how many new records were added to the database and by who over time.