I am teaching a database class at Queens College. The project entails the truncation of all of the data and loading new data into the existing database "BIClass" from a single of the flattened data. One of the tasks of the project was to add these three additional columns to each of the tables (AlterTableAddColumnsUserAuthorizationKeyAndTwoTimeStamps):
- [UserAuthorizationKey] [int] not null DEFAULT (-99)
- [DateAdded] [datetime2](7)] not null DEFAULT (sysdatetime())
- [DateOfLastUpdate] [datetime2](7)] not null DEFAULT (sysdatetime())
The goal was to leverage the TSQL topics being taught:
- Built-in functions such as concat to create the alter table command
- Metadata views to find fully qualified table names using either INFORMATION_SCHEMA.TABLES (easier) or sys.tables
- Create a query using a set operation such as union
- Create schema names such as Utils (Utility objects)
- Create a view with our convention in this case Utils.uvw_UtilityObjectName. In our case, Utils.uvw_AlterTableAddColumnsUserAuthorizationKeyAndTwoTimeStamps
Sample code:
Execution of this query returned 66 rows since there were 22 tables.
SELECT v.SchemaName,
v.FullyQualifiedTableName,
v.SortOrder,
v.AlterFullyQualifiedTableNameAddingColumn
FROM Utils.uvw_AlterTableAddColumnsUserAuthorizationKeyAndTwoTimeStamps AS v
ORDER BY v.FullyQualifiedTableName,
v.SortOrder;
-- Before Adding the three columns
CREATE TABLE [dbo].[Digits](
[digit] [INT] NOT NULL
) ON [PRIMARY]
GO
-- Add the three columns
ALTER TABLE dbo.Digits add [UserAuthorizationKey] [int] not null DEFAULT(-99)
ALTER TABLE dbo.Digits add [DateAdded] [datetime2](7) not null DEFAULT(sysdatetime())
ALTER TABLE dbo.Digits add [DateOfLastUpdate] [datetime2](7) not null DEFAULT(sysdatetime())
-- After Adding the three columns
CREATE TABLE [dbo].[Digits](
[digit] [INT] NOT NULL,
[UserAuthorizationKey] [INT] NOT NULL,
[DateAdded] [DATETIME2](7) NOT NULL,
[DateOfLastUpdate] [DATETIME2](7) NOT NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Digits] ADD DEFAULT ((-99)) FOR [UserAuthorizationKey]
GO
ALTER TABLE [dbo].[Digits] ADD DEFAULT (SYSDATETIME()) FOR [DateAdded]
GO
ALTER TABLE [dbo].[Digits] ADD DEFAULT (SYSDATETIME()) FOR [DateOfLastUpdate]
GO
It teaches a simple way to automate a repetitive task as well as leveraging the use of metadata.