SQL Server 2022 : Establish a default value and a time stamp
Establish a default value might be useful, it's fun to learn something new.
Let's assume that I'm going to add new records to the table which belongs to one single category, and I want it generate automatically each time when I key in the new record. I'm going to use the Products table this time. Open the design window and select Category from the Column Name, then move down to the Column Properties. Type 'eBooks' to 'Default Value or Binding', SQL server will automatically turn it into '(N'ebooks')'. The N character means that this will use the Unicode character set and the data type for Category is nvarchar(50) which supports the Unicode.
Now save this change and let's test if it works. Go to Object Explorer, select table name, right click and press 'Edit Top 200 Rows'.
Add a new record, fill the info to each column of table product, skip the Category column for now.
Then press enter, and Voila! SQL server fills out the category column with 'eBook' as a default value automatically without link to any other columns.
We can also let the system to add timestamp to the new added record each time automatically which is quite useful. Go back to the Design window of table Products, add a new column 'TimeStamp', set the Data Type as 'datetime2(7)'. For 'Default Value or Binding', put getdate() function there which returns the current database system date and time when new record is created.
Notes: I use the sample database from Microsoft SQL Server 2022 Essential Training With Adam Wilbert.
Comments
Post a Comment