The Default Value of a Column |
|
Sometimes most records under a certain column may hold the
same value although just a few would be different. For example, if a school is
using a database to register its students, all of them are more likely to be
from the same state. In such a case, you can assist the user by automatically providing
a value for that column. The user would then simply accept the value and change
it only in the rare cases where the value happen to be different. To assist the
user with this common value, you create what is referred to as a default value.
Visually Creating a Default Value |
|
You can create a default value of a column when creating a
table. To specify the default value of a column, in the top section, click the
column. In the bottom section, click Default Value or Binding, type the desired
value following the rules of the column's data type:
It the Data Type is |
Intructions |
Text-based (char, varchar, text,
and their variants) |
Enter the value in single-quotes |
Numeric-based |
Enter the value as a number but
following the rules of the data type.
For example, if you enter a value higher than 255 for a tinyint,
you would receive an error |
Date or Time |
Enter the date as either
MM/DD/YYYY or YYYY/MM/DD. You can optionally include the date in
single-quotes.
Enter the time following the rules set in the Control Panel (Regional
Settings). |
Bit |
Enter the value as 0 for FALSE or
any other long integer value for TRUE |
Programmatically Creating a Default Value |
|
To specify the default value in a SQL statement, when
creating the column, before the semi-colon or the closing parenthesis of the
last column, assign the desired value to the DEFAULT keyword. Here are
examples:
CREATE TABLE Employees
(
FullName VARCHAR(50),
Address VARCHAR(80),
City VARCHAR(40),
State VARCHAR(40) DEFAULT = 'NSW',
PostalCode VARCHAR(4) DEFAULT = '2000',
Country VARCHAR(20) DEFAULT = 'Australia'
);
GO
After creating the table, the user does not have to provide a
value for a column that has a default. If the user does not provide the value,
the default would be used when the record is saved.
|
If the user provides a value for a column that has a
default value and then deletes the value, the default value rule would not
apply anymore: The field would simply become empty |
One of the goals of a good table is to be able to
uniquely identity each record. In most cases, the database engine should
not confuse two records. Consider the following table:
Category |
Item Name |
Size |
Unit Price |
Women |
Long-sleeve jersey dress |
Large |
39.95 |
Boys |
Iron-Free Pleated Khaki Pants |
S |
39.95 |
Men |
Striped long-sleeve shirt |
Large |
59.60 |
Women |
Long-sleeve jersey dress |
Large |
45.95 |
Girls |
Shoulder handbag |
|
45.00 |
Women |
Continental skirt |
Petite |
39.95 |
Imagine that you want to change the value of an item
named Long-sleeve jersey dress. Because you must find the item
programmatically, you can start looking for an item with that name. This
table happens to have two items with that name. You may then decide to
look for an item using its category. In the Category column, there are too
many items named Women. In the same way, there are too many records that
have a Large value in the Size column, same thing problem in the Unit
Price column. This means that you don't have a good criterion you can use
to isolate the record whose Item Name is Long-sleeve shirt.
To solve the problem of uniquely identifying a record,
you can create a particular column whose main purpose is to distinguish
one record from another. To assist you with this, the SQL allows you to
create a column whose data type is an integer type but the user doesn't
have to enter data for
that column. A value would automatically be entered into the field when a
new record is created. This type of column is called an identity column.
You cannot create an identity column one an existing
table, only on a new table.
Visually Creating an Identity Column |
|
To create an identity column, if you are visually
working in the design view of the table, in the top section, specify the
name of the column. By tradition, the name of this column resembles that
of the table but in singular. Also, by habit, the name of the column ends
with _id, Id, or ID.
After specifying the name of the column, set its data
type to an integer-based type. Usually, the data type used is int. In the bottom section, click
and expand the Identity Specification property. The first action
you should take is to set its (Is Identity) property from No to Yes.
Once you have set
the value of the (Is Identity) property to Yes, the first time the
user performs data entry, the value of the first record would be set to 1.
This characteristic is controlled by the Identity Seed property. If
you want the count to start to a value other than 1, specify it on this
property.
After the (Is Identity) property has been set to Yes, the
SQL interpreter would increment the value of each new record by 1, which
is the default. This means that the first record would have a value of 1, the second would have a value of
2, and so on. This aspect is controlled by the Identity Increment
property. If you want to increment by more than that, you can change
the value of the Identity Increment property.
Practical
Learning: Creating an Identity Column in the Design Table
|
|
- In the Object Explorer, under WorldStatistics, right-click Tables
and click New Table...
- Set the name of the column to ContinentID and press Tab
- Set its data type to int and press F6.
In the lower section of the table, expand Identity Specification and
double-click (Is Identity) to set its value to Yes
- Complete the table as follows:
Column Name |
Data Type |
Allow Nulls |
ContinentID |
|
|
Continent |
varchar(80) |
Unchecked |
Area |
bigint |
|
Population |
bigint |
|
- Save the table as Continents
Creating an Identity Column Using SQL |
|
If you are programmatically creating a column, to
indicate that it would be used as an identity column after its name and
data type, type identity followed by parentheses. Between the
parentheses, enter the seed value, followed by a comma, followed by the increment
value. Here is an example:
CREATE TABLE StoreItems(
ItemID int IDENTITY(1, 1) NOT NULL,
Category varchar(50),
[Item Name] varchar(100) NOT NULL,
Size varchar(20),
[Unit Price] money);
GO
You can involve a function during data entry. As an
example, you can call a function that returns a value to assign that value
to a column. You can first create your own function and use it, or you can
use one of the built-in functions.
In order to involve a function with your data entry,
you must have and identity one. You can use one of the built-in functions
of Transact-SQL. You can check one of the functions we reviewed in Lesson
7. Normally, the best way is to check the online documentation to find
out if the assignment you want to perform is already created. Using a
built-in function would space you the trouble of getting a function. For
example, imagine you have a database named AutoRepairShop and imagine it
has a table used to create repair orders for customers:
CREATE TABLE RepairOrders
(
RepairID int Identity(1,1) NOT NULL,
CustomerName varchar(50),
CustomerPhone varchar(20),
RepairDate DateTime
);
GO
When performing data entry for this table, you can let
the user enter the customer name and phone number. On the other hand, you
can assist the user by programmatically entering the current date. To do
this, you would call the GETDATE()
function. Here are examples:
INSERT INTO RepairOrders(CustomerName, CustomerPhone, RepairDate)
VALUES('Annette Berceau', '301-988-4615', GETDATE());
GO
INSERT INTO RepairOrders(CustomerPhone, CustomerName, RepairDate)
VALUES('(240) 601-3795', 'Paulino Santiago', GETDATE());
GO
INSERT INTO RepairOrders(CustomerName, RepairDate, CustomerPhone)
VALUES('Alicia Katts', GETDATE(), '(301) 527-3095');
GO
INSERT INTO RepairOrders(RepairDate, CustomerPhone, CustomerName)
VALUES(GETDATE(), '703-927-4002', 'Bertrand Nguyen');
GO
You can also involve the function in an operation,
then use the result as the value to assign to a field. You can also call a
function that takes one or more arguments; make sure you respect the rules
of passing an argument to a function when calling it.
If none of the Transact-SQL built-in functions
satifies your requirements, you can create your own, using the techniques
we studied in Lesson 6.
Using Expressions For Data Entry |
|
There are various ways you can assist the user with
data entry. Besides using a function, you can create an expression using
operators such as those we reviewed in lessons 3 and 5. You can create an
expression when creating a table, whether in the Table window or using SQL
in a query window.
Visually Creating an Expression |
|
To create an expression when visually creating a
table, in the top section, specify the column's name (only the column name
is important). In the bottom section, expand the Computed Column
Specification field and, in its (Formula) field, enter the desired
expression. Here is an example:
Creating a SQL Expression |
|
You can also create an expression in SQL expression
you are using to create a table. To do this, in the placeholder of the
column, enter the name of the column, followed by AS, and followed by the
desired expression. Here is an example:
CREATE TABLE Circle
(
CircleID int identity(1,1) NOT NULL,
Radius decimal(8, 3) NOT NULL,
Area AS Radius *Radius * PI()
);
GO
Using an Expression During Data Entry |
|
When performing data entry, you must not provide a
value for a column that has an expression; the SQL interpreter would
provide the value automatically. Here is an example of entering data for
the above Circle table:
INSERT INTO Circle(Radius) VALUES(46.82);
GO
INSERT INTO Circle(Radius) VALUES(8.15);
GO
INSERT INTO Circle(Radius) VALUES(122.57);
GO
When performing data entry, in some columns, even
after indicating the types of values you expect the user to provide for a
certain column, you may want to restrict a range of values that are allowed.
To assist you with checking whether a newly entered value fits the desired
range, Transact-SQL provides what is referred to as a check constraint.
A check constraint is a Boolean operation performed
by the SQL interpreter. The interpreter examines a value that has just been
provided for a column. If the value is appropriate:
- The constraint produces TRUE
- The value gets accepted
- The value is assigned to the column
If the value is not appropriate:
- The constraint produces FALSE
- The value gets rejected
- The value is not assigned to the column
You create a check constraint at the time you are creating a
table.
Visually Creating a Check Constraint |
|
To create a check constraint, when creating a table,
right-click anywhere in (even outside) the table and click Check
Constraints...
This would open the Check Constraints dialog box. From that
window, you can click Add. Because a constraint is an object, you must provide a name for it. The most important
piece of information that a check constraint should hold is the mechanism it
would use to check its values. This is provided as an expression. Therefore, to
create a constraint, you can click Expression and click its ellipsis button.
This would open the Check Constraint Expression dialog box.
To create the expression, first type the name of the column
on which the constraint will apply, followed by parentheses. In the parentheses,
use the arithmetic and/or SQL operators we studied already. Here is an example
that will check that a new value specified for the Student Number is greater
than 1000:
After creating the expression, you can click OK. If the
expression is invalid, you would receive an error and given the opportunity to
correct it.
You can create as many check constraints as you judge
necessary for your table:
After creating the check constraints, you can click OK.
Programmatically Creating a Check Constraint |
|
To create a check constraint in SQL, first create the
column on which the constraint will apply. Before the closing parenthesis of the table definition, use the
following formula:
CONSTRAINT name CHECK (expression)
The CONSTRAINT and the CHECK keywords are
required. As an object, make sure you provide a name for it. Inside the
parentheses that follow the CHECK operator, enter the expression that will be
applied. Here is an example that will make sure that the hourly salary specified
for an employee is greater than 12.50:
CREATE TABLE Employees
(
[Employee Number] nchar(7),
[Full Name] varchar(80),
[Hourly Salary] smallmoney,
CONSTRAINT CK_HourlySalary CHECK ([Hourly Salary] > 12.50)
);
It is important to understand that a check constraint it
neither an expression nor a function. A check constraint contains an expression
and may contain a function as part of its definition.
After creating the constraint(s) for a table, in the Object
Explorer of Microsoft SQL Server Management Studio, inside the table's node,
there is a node named Constraints and, if you expand it, you would see the name
of the constraint.
With the constraint(s) in place, during data entry, if the
user (or your code) provides an invalid value, an error would display. Here is
an example:
Instead of an expression that uses only the regular
operators, you can use a function to assist in the checking process. You can
create and use your own function or you can use one of the built-in Transact-SQL
functions.
Other Features of Data Entry |
|
This property allows you to specify
that a column with the Identity property set to Yes is used as a
ROWGUID
column.
Because different languages use
different mechanisms in their alphabetic characters, this can affect the
way some sort algorithms or queries are performed on data, you can ask the
database to apply a certain language mechanism to the field by changing the
Collation property. Otherwise, you should accept the default specified by
the table.
Another technique used to get data into one or more
tables consists
of importing already existing data from another database or from any other
recognizable data file. Microsoft SQL Server provides various techniques
and means of importing data.
The easiest type of data that can be imported into SQL
Server, and which is available on almost all database environments, is the
text file. Almost every database environment allows you to import a
text file but data from that file must be formatted appropriately. For example, the information stored in the file must define the
columns as distinguishable by a character that serves as a separator. This
separator can be the single-quote, the double-quote, or any valid
character. Data between the quotes is considered as belonging
to a distinct field. Besides this information, the database would need to
separate information from two different columns. Again, a valid character
must be used. Most databases, including Microsoft SQL Server, recognize the comma as
such a character. The last piece of information the file must provide is
to distinguish each record from another. This is easily taken car of by
the end of line of a record. This is also recognized as the carriage
return.
These directives can help you manually create a text
file that can be imported into Microsoft SQL Server. In practicality, if you want to
import data that resides on another database, you can ask that application
to create the source of data. Most applications can do that and format the
data. That is the case for
the data we will use in the next exercise: it is data that resided on a
Microsoft Access database and was prepared to be imported in Microsoft SQL Server.
After importing data, you should verify and possibly
format it to customize its fields.
Practical
Learning: Importing Data From an External Source
|
|
- Download the Students text file and save
it to your hard drive
- In the SQL Server Management Studio, right-click the Databases node and click
New Database...
- Type ROSH and press Enter
- In the Object Explorer, right-click ROSH, position the mouse on
Tasks and click Import Data
- On the first page of the wizard, click Next
- On the second page, click the arrow of the Data Source combo box and
select Flat File Source
- On the right side of File Name, click the Browse button
- Locate and select the Students.txt file you had saved
- Under Data Source, click Advanced
- As Column is selected, in the right list, click Name and type
StudentID
- In the middle list, click each column and change its Name in the
right column as follows:
Column |
Name |
Column0 |
StudentID |
Column1 |
FirstName |
Column2 |
LastName |
Column3 |
DateOfBirth |
Column4 |
Gender |
Column5 |
Address |
Column6 |
City |
Column7 |
State |
Column8 |
ZIPCode |
Column9 |
HomePhone |
Column10 |
EmailAddress |
Column11 |
ParentsNames |
Column12 |
SPHome |
Column13 |
EmrgName |
Column14 |
EmrgPhone |
- To see the list of columns, under Data Source, click Columns
- Click Next 4 times
- Click Finish
- Click Close
- Back in the Object Explorer, expand the ROSH and its Tables nodes.
Right-click Students and click Design
- As the StudentID
field is selected, press Tab and change its
data type to int
- Press F6 and expand Identity Specification.
Double-click (Is Identity) to set its value to Yes
- Change the other columns as follows:
- To save the table, click the Save button on the Standard toolbar:
- When a Validation Warnings dialog box presents a few warnings, click
Yes
- Close the table
- To view data stored on the table, in the Object Explorer, right-click
dbo.Students and click Open
Table
Checking the Existence of a Record |
|
One of the simplest operations a user can perform on a
table consists of looking for a record. To do this, the user would open
the table that contains the records and visually check them, looking for a
piece of information, such as a student's last name.
As the database developer, you too can look for a
record and there are various techniques you can use. To assist you with
this, Transact-SQL provides a function named EXISTS. Its syntax is:
BIT EXISTS(SELECT Something)
This function takes one argument. The argument must be
a SELECT statement that would be used to get the value whose
existence would be checked. For example, in Lesson
2, we mentioned a system database names databases that contains
a record of all databases stored on your server. You can use the EXISTS()
function to check the existence of a certain database. The formula you
would use is:
IF EXISTS (
SELECT name
FROM sys.databases
WHERE name = N'DatabaseName'
)
In the DatabaseName placeholder, you can enter
the name of the database.
Before visually performing some operations on a table,
you must first select one or more records. In the Table window, to select
one record, position the mouse on the left button of the record and click:
To select a range of records, click the gray button of
one of the records, press and hold Shift, then click the gray button of
the record at the other extreme.
To select the records in a random fashion, select one
record, press and hold Ctrl, then click the gray button of each desired
record:
To select all records of a table, click the gray
button on the left of the first column:
To visually modify one or more records on a table,
first open it (you right-click the table in the Object Explorer and click
Open Table) to view its records. Locate the record and the field you want
to work on and perform the desired operation.
Record maintenance includes viewing records, looking
for one or more records, modifying one or more records, or deleting one or
more records.
Updating a record consists of changing its value for
a particular column. To update a record using SQL:
- In the Object Explorer, you can right the table, position the mouse on
Script Table As -> UPDATE To -> New Query Editor Window
- Open an empty query window and type your code
To support record maintenance operations, the SQL provides the UPDATE keyword
that is used to specify the table on which you want to maintain the
record(s). The basic formula to use is:
UPDATE TableName
SET ColumnName = Expression
With this formula, you must specify the name of the
involved table as the TableName factor of our formula. The SET
statement allows you to specify a new value, Expression, for the
field under the ColumnName column.
Consider the following code to create a new database
named VideoCollection and to add a table named Videos to it:
CREATE DATABASE VideoCollection;
GO
USE VideoCollection;
GO
CREATE TABLE Videos (
VideoID INT NOT NULL IDENTITY(1,1),
VideoTitle varchar(120) NOT NULL,
Director varchar(100) NULL,
YearReleased SMALLINT,
VideoLength varchar(30) NULL,
Rating varchar(6)
);
GO
INSERT INTO Videos(VideoTitle, Director, YearReleased, VideoLength)
VALUES('A Few Good Men','Rob Reiner',1992,'138 Minutes');
INSERT INTO Videos(VideoTitle, Director, YearReleased, VideoLength)
VALUES('The Silence of the Lambs','Jonathan Demme',1991,'118 Minutes');
INSERT INTO Videos(VideoTitle, Director, VideoLength)
VALUES('The Distinguished Gentleman', 'James Groeling', '112 Minutes');
INSERT INTO Videos(VideoTitle, Director, VideoLength)
VALUES('The Lady Killers', 'Joel Coen & Ethan Coen', '104 Minutes');
INSERT INTO Videos(VideoTitle, Director, VideoLength)
VALUES('Ghosts of Mississippi', 'Rob Reiner', '130 Minutes');
GO
Imagine that, at one time, on a particular table, all
records need to receive a new value under one particular column or certain
columns. There is no particular way to visually update all records of a
table. You can just open the table to view its records, and then change
them one at a time.
In SQL, the primary formula of the UPDATE statement as introduced
on our formula can be used to update all records. Here is an example:
USE VideoCollection;
GO
UPDATE Videos
SET Rating = 'R';
GO
With this code, all records of the Videos table will have
their Rating fields set to a value of R:
Editing a record consists of changing a value in a
field. It could be that the field is empty, such as the © Year of the
the 'The Lady Killers' video of the
following table. It could be that the value is wrong, such as the Director of
the the 'The Distinguished Gentleman' video of this table:
Video Title |
Director |
© Year |
Length |
Rating |
A Few Good Men |
Rob Reiner |
1992 |
138 Minutes |
R |
The Silence of the Lambs |
Jonathan Demme |
1991 |
118 Minutes |
|
The Distinguished Gentleman |
James Groeling |
|
112 Minutes |
R |
The Lady Killers |
Joel Coen & Ethan Coen |
|
104 Minutes |
R |
Ghosts of Mississippi |
Rob Reiner |
|
130 Minutes |
|
To edit a record, first open the table to view its records.
Locate the record, the column on which you want to work, and locate the value
you want to change, then change it.
In SQL, you must provide a way for the interpreter
to locate the record. To do this, you would associate the WHERE operator
in an UPDATE statement using the following formula:
UPDATE TableName
SET ColumnName = Expression
WHERE Condition(s)
The WHERE operator allows you to specify how the
particular record involved would be identified. It is very important, in
most cases, that the criterion used be able to uniquely identify the record. In
the above table, imagine that you ask the interpreter to change the released
year to 1996 where the director of the video is Rob Reiner. The UPDATE statement
would be written as follows:
UPDATE Videos
SET YearReleased = 1996
WHERE Director = 'Rob Reiner';
In the above table, there are at least two videos directed
by Rob Reiner. When this statement is executed, all video records whose director
is Rob Reiner would be changed, which would compromise existing records that
didn't need this change. This is where the identity column becomes valuable. We saw
earlier that, when using it with the IDENTITY feature, the interpreter appends a unique value to each record. You can then use
that value to identify a particular record because you are certain the value is
unique.
Here is an example used to specify the missing copyright year of a particular
record:
UPDATE Videos
SET YearReleased = 1996
WHERE VideoID = 5;
GO
Here is an example used to change the name of the director of a particular
video:
UPDATE Videos
SET Director = 'Jonathan Lynn'
WHERE VideoTitle = 'The Distinguished Gentleman';
If you think all records of a particular table are, or have
become, useless, you can clear the whole table, which would still keep its
structure. To delete all records from a table, first select all of them,
and press Delete. You would receive a warning:
If you still want to delete the records, click Yes. If
you change your mind, click No.
Using SQL, to clear a table of all records, use the DELETE
operator with the following formula:
DELETE TableName;
When this statement is executed, all records from the TableName
factor would be removed from the table. Be careful when doing this because
once the records have been deleted, you cannot get them back.
If you find out that a record is not necessary, not
anymore, or is misplaced, you can remove it from a table. To remove a
record from a table, you can right-click its gray box and click Delete.
You can also first select the record and press Delete. You would receive a
warning to confirm your intention.
To delete a record using SQL:
- In the Object Explorer, you can right the table, position the mouse on
Script Table As -> DELETE To -> New Query Editor Window
- Open an empty query window and type your code
In SQL, to delete a record, use the DELETE FROM statement associate the WHERE
operator. The formula to follow is:
DELETE FROM TableName
WHERE Condition(s)
The TableName factor is used to identify a
table whose record(s) would be removed.
The Condition(s) factor allows you to identify
a record or a group of records that carries a criterion. Once again, make
sure you are precise in your criteria so you would not delete the wrong
record(s).
Here is an example used to remove a particular record from the
table:
DELETE FROM Videos
WHERE VideoTitle = 'The Lady Killers';
Here is an example used to clear the table of all videos:
DELETE FROM Videos;
Practical Learning: Ending the Lesson
|
|
- Close the query window without saving the file
- In the Object Explorer, under the Databases node, right-click
WorldStatistics and click Delete
- In the dialog box, click OK
- Record
- Row
- Table Navigation
- Visual Data Entry
- SQL Data Entry
- Adjacent Data Entry
- Random Data Entry
- Default Values
- Identity Columns
- Expressions
- Check Constraints
- Collation
- Data Import
- Selecting Records
- Editing Records
- Updating Records
- Deleting Records
Keywords, Operators, and Properties
|
|
- NULL
- NOT NULL
- DEFAULT
- IDENTITY
- Identity Specification
- (Is Identity)
- Identity Seed property
- Identity Increment
- CONSTRAINT
- CHECK
- Collation
- databases
- EXISTS
- UPDATE
- DELETE
|