Database Management Study Guide - DBMM-16 V1.1
Database Management Study Guide - DBMM-16 V1.1
DBMM-16
Database Management
DBMM-16
Compiled by: Luke Burgess, Trudie Lotz, Lance Whyte, Cedric Maenetja
and Nceba Matandabuzo
Version 1.1
Introduction 1
Description 1
Assessment for pass 2
Reference books 3
How to approach this course 3
Structure of a unit 4
Beginning a project 5
System requirements 10
Icons used in the study guide 11
Unit 2 – Transact-SQL 29
2.1 SQL Server storage concepts 29
2.2 Transact-SQL 31
2.3 GO statements 38
2.4 Basic modifiers 42
2.5 Integrity 46
2.6 Indentation and neatness 51
Glossary 152
Bibliography 153
The course starts with the fundamentals of database design concepts. From
there on, the concepts of creating a database are covered as well as populating
and implementing the functions of a database.
A number of other topics are covered, including indexes, joins, views, stored
procedures and triggers, which are all used either to retrieve or to update data
in a database, as well as database security and how to back up a database.
At the end of the course, students will have to incorporate the concepts taught
into a project. This project will also require user documentation. The user
documentation will consist of author details, installation details, design details
and any extra information that may be relevant to the project.
Students will also have to incorporate their knowledge into a theoretical and a
practical examination. The theory will be written at the end of the course and
the practical will be done after the theory examination. The practical
examination tests the student’s ability to create a database and apply functions
to the database. Although not all concepts are tested in one practical
examination as this would take too long to complete, the most important
concepts will be tested.
Welcome to CTI’s Microsoft SQL Server course. SQL stands for Structured
Query Language and it is pronounced by sounding out each letter or by saying
‘seequil’. This book will be your study guide for the next few weeks. You do not
need any prior SQL Server knowledge other than what you learnt in the
Database Design Concepts course. Microsoft Windows experience is not
required but it is useful because many of the optional features of SQL Server
require interaction with the Windows environment.
Supplementary reference books that may be borrowed from the library for
further understanding will be listed in the Bibliography. This supplementary
reading is not mandatory, but it will certainly help you to answer some of the
intermediate and advanced questions in the exams. This reference material will
be a great aid if you would like to know more or gain a different perspective on
what you have learnt in this course.
NOTE
To access SQL Server Book online for Microsoft SQL Server 2014, ensure the
documentation feature is installed when installing the program. For more
details about this, visit Aaron Bertrand’s blog:
http://sqlblog.com/blogs/aaron_bertrand/archive/2014/04/23/yes-you-can-
install-sql-server-2014-books-online-locally.aspx
Instructions are provided.
After your project has been marked, you will have time to prepare for and
write the examination. You have a certain number of days to complete the
course. The course breakdown is shown in Table 2.
Structure of a unit
All the units follow the same structure. You will be presented with the
outcomes for each unit. These outcomes can be used as an indication of what
is important and what you should focus on when going through the unit’s
material. Notes will follow this. Read these sections carefully. Key terms will
list what you should have read and understood in the unit.
You will be presented with exercises that will require you to apply your
knowledge of the material. Ensure that you understand the exercises. Ask for
help if you are unsure of what to do. Revision questions will give you an
indication of what to expect in the exam, although you should not rely on these
questions as your only reference. Some exam questions will undoubtedly be more
difficult than the revision questions.
You will find the project specifications at the end of the study guide. Please
do not start working on the project until you have completed (and understood)
all the exercises. Once you have covered all the topics from the previous units
and you are satisfied that you have met the outcomes, you may start the
project.
Use the project specifications as a guide. They will list everything that you
need to do to comply with the project’s requirements. If your project does not
comply with these requirements, it will not be marked. Please see the mark
sheets for each project. These indicate how the marks will be allocated.
Beginning a project
It is suggested that you read through your project as soon as you receive your
new study guide. This will give you an idea of what is expected in the project.
As you progress through the guide, you will start identifying how to approach
the project. You should only start on your project once you have worked
through the entire study guide and have a good understanding of the material.
Performing the following steps will help to ensure that you complete your
project successfully:
1. Read the relevant section in the study guide to familiarise yourself with the
material.
2. Type the examples. This might seem pointless, but it is an easy way to
familiarise yourself with the language. Experiment with the code; make
deliberate mistakes to get a feel for the way in which the compiler handles
errors.
3. Complete the exercises at the end of every chapter in the reference book. The
best way to learn a language is to practise it. This will also help you in the
examination.
4. Only start with the project if you feel comfortable with the material.
5. Make use of textbooks when the need arises.
If you work according to these guidelines, you should find that the projects are
not too difficult.
Program design
You must follow the project specifications. For example, if the project
specifications instruct you to use a specific class, you will need to use that
class. You will be allowed to be creative, but you will be required to incorporate
certain elements into the project.
The first step in any program development cycle should be a design phase –
what exactly it is that you want to do, and how you will achieve it.
Source code
For any serious program that you develop, it is almost guaranteed that either
you or another programmer will have to return to the code on occasion to
correct a problem or add a new feature. It is thus important that your code is
easy to read. One way to make code easy to read is by using indentation and
white space.
Your code should also contain comments that clearly explain what is intended
by structures and blocks in the code. If a programmer who has to maintain the
code has to try to understand what it was that you intended originally, it not
only wastes time but also opens up the possibility that the intention may be
misunderstood, which may lead to further problems.
The program source code must be clear and well laid out.
You must follow a set naming standard for variable and method names.
Method and variable names should be descriptive.
Each file must be clearly labelled, with a prologue displaying the following
details in comments:
o Name of the file
o Name of the author
o Date created
o Operating system
o Version
o Description of the code
For example:
The source code must be printed and submitted with your final project
submission (this includes any projects submitted electronically).
The program does not run or there are warnings of any kind. Your program
must compile and work properly before you submit it. If your program
does not run correctly, you will fail the project and you will need to
redo it.
If you follow the project specification and your program runs without any
extra effort, you should receive at least 60% for the project.
User interface
Display money values with an appropriate symbol (e.g. R, £ or $) and
percentages with the percentage symbol (%).
User documentation
All programs should be adequately documented:
Those who have to maintain the code must know what was intended by
every single line of code (called program design documentation and source
code documentation).
Those who have to use the program must know how to run it, what to
expect and what output will be displayed or printed (called user
documentation).
You should supply extensive descriptions for your classes and members.
Documentation must be in the form of a Word document unless stated
otherwise.
The user documentation must adequately explain how to install and run the
application, working on the assumption that the end-user has no prior
experience in doing so.
The user documentation must explain how to use each feature of the
application. The screenshots included must clarify each operation.
The user documentation must be printed and submitted with your final project
submission (this includes any project submitted electronically).
Project documentation
Your project documentation must include all of the following when your project
is submitted:
Project specification
Program design
Project source code
User documentation
Databases (if any)
Resources (if any)
System requirements (if any)
Rough work (if any)
NOTE
All projects must be presented in a professional format. Treat your project
submissions as you would in the working environment. Documentation
should be neat and typed. Ensure that you run a spell check on your project
before you submit. All your projects will make up your portfolio of evidence
which you can present to your future employer to show what you have
completed as a student.
Points out the keywords for each section. Ensure that you can
name and explain all the keywords before proceeding to the
next section.
A primary key does not change, and is explicitly generated when data is
created.
Only one primary key can be assigned per table.
Primary keys must represent unique values.
A primary key should be data free. This helps when database data changes
as the primary key will not have to be changed.
1.2 Relationships
Relationships are the link between two tables. Three types of relationships can
exist between any two tables: one-to-one, one-to-many and many-to-
many.
1.3 Normalisation
Normalisation is used to ensure an optimum and efficient structure for any
database. It consists of a set of rules that improve a database’s design. Using
a number of ‘forms’, the design is refined with each higher normal form. One
of the main reasons that it improves efficiency is that it resolves many-to-
many relationships.
NOTE
Please refer back to the Database Design Concepts course for a reminder
on normalisation. The following video will also be a useful reminder:
Richard Grant, Implementing 1NF, 2NF, 3NF here [Accessed: 25
September 2015]
1. Formulate a mission statement for the system that you are designing. Also
specify the system requirements.
2. Draw up rough diagrams of the data entry forms envisaged for the
system.
5. Make sure that the tables in Step 3 include the data in the reports.
8. Identify and specify the foreign keys. Create relationships between tables.
9. Check whether all tables are in first normal form. Make adjustments if
necessary.
10. Check whether all tables are in second normal form. Make adjustments if
necessary.
13. Create the improved tables and add the sample data.
14. Draw up conceptual forms, queries and reports. Adjust your design if
necessary.
15. Obtain feedback from the users. Adjust and re-normalise if necessary.
17. Create the refined forms, queries and reports. Design and develop the
associated application. Adjust your design if necessary.
18. Obtain feedback through user testing. Adjust your design if necessary.
There are a few things you should know before installing SQL Server 2014:
If you are planning to use one server, all previous versions of SQL Server
must be removed. There is also an option to upgrade from these older
versions, which could prove to be rather useful if you would like to migrate
all your current data to the new server.
If a Windows version earlier than Windows 7 service pack 1 is used, the
.NET framework must be installed before the process of installing SQL
Server 2014 can begin (version 3.5 SP1 is recommended).
Windows 8 comes with .NET 3.5 framework; to enable this feature, see the
note block after these installation guidelines.
Depending on what version of SQL Server is being installed, Internet access
may be required for the installation to complete successfully because SQL
may need to download files that are out of date or missing.
You must be an administrative user.
First the .NET framework SP1 must be installed. This is sometimes included on
the SQL Server 2014. If so, it will run automatically. If your disk did not come
with the .NET framework, the setup will very likely try to download the
necessary files. If it does not, you will need to download and run them
manually from www.microsoft.com/NET. Before the .NET framework starts
Once you have accepted the licence agreement and clicked on Install, the
setup will start downloading and installing the necessary files, as shown in
Figure 3 – Installing .NET framework. The .NET framework will be explained in
the next unit.
After this, it will indicate that the setup has completed successfully. If it does
not, make sure that your Internet connection is set up correctly. Your
computer may need to restart in order for the changes to take effect. Once
your computer has rebooted, you may proceed to install SQL Server 2014.
NOTE
In case you are working on Windows 8, there will be no need for you to
download the .NET framework. Just follow the simple steps to enable the
feature in the control panel. In this regard, visit the following link: here
This will require a connection to the Internet because the file needs to
download.
The first screen that you will be presented with is the SQL Server Installation
Center, when the SQL Server 2014 setup is run. Click on the Installation
option. You will be presented with a list of different installation options, as
shown in:
The other options include other useful features that Microsoft offers in relation
to their product, such as support. If you click on the Resources option, useful
help material such as Books Online will be displayed. You may do your own
research into the other options but they will not be covered in this course.
Click on the Installation option and select New SQL Server stand-alone
installation or add features to an existing installation.
The next step is to select the product type you wish to use. Here the options
are Evaluation and Product key version (which can be Enterprise or
Standard edition).
Click NEXT and read through the MICROSOFT LICENSE SOFTWARE TERMS
and check the box to accept the terms. You should choose to turn on customer
experience improvement as well; then click NEXT.
The next step will first run a test on your system and attempt to predict
whether or not the installation might fail. It should pass all tests of the Setup
Support Rules before you can proceed.
Click OK, and then NEXT on the next screen. It will take a few minutes to
perform a second batch of tests (see Figure 5 – Setup Support Rules).
The next step in the SQL Server 2014 Setup is selecting which features of the
SQL Server you would like to install (see Figure 6 – Feature selection).
Click on Select All so that all the available features will be installed. However,
if you do not have enough space, consult one of the prescribed books for
selection of the components. The next screen that is displayed configures the
SQL Server instance. Some businesses require more than one instance of SQL
Server to be running at any given time; that is why you can install many SQL
Servers on one computer as long as they are specified as separate instances.
There can only be one default instance and the rest have to be named. Each
instance must have an instance ID as well as a unique instance directory. The
pane at the bottom of the window shows the current instances installed on
your PC (see Figure 7 – Instance Configuration). Make your instance of SQL
Server the default instance and leave the rest as it is. Click Next to continue.
The next screen will inform you of how much space is required and how it is
allocated. Click Next to go to the Server Configuration screen to set up the
passwords. Click on the Use the same account for all SQL Server services
button. Enter a valid user name and password for your PC (preferably
Administrator) and click OK. All the services will be set to the same account,
as shown in Figure 8 – Server Configuration.
NOTE
Please note that the account username is hidden for security reasons.
However, this is your Windows administrative account or server if you are
connected to a network server.
Click Next. If errors appear at the bottom of your window, you have not
entered a correct user name and password. Once a valid user name and
password have been accepted, you will be presented with the database engine
configuration window.
On the next screen (Analysis Services Configuration) you can also add the
current user to the Account Provisioning pane.
The next window performs more tests. Check it and proceed to the next
window, which summarises exactly what is going to be installed. When you
have checked this and are ready to install, click the Install button. SQL Server
2014 will begin installing, as shown in Figure 10 – Installation Progress.
After the installation is complete, you will need to restart your PC manually.
SQL Server will not run properly until you have restarted your PC.
NOTE
If you encounter any problems or issues during the installation process,
see the prescribed textbook or check other resources: Check the YouTube
video: SmodTech, SQL SERVER 2014 Installation Free: here [Accessed:
20 September 2015], or alternatively on the Microsoft website here
[Accessed: 25 September 2015] or the SQLCoffee website: here
[Accessed: 25 September 2015]
Registered servers: This is a new concept in SQL Server 2014 which depicts
a division managing servers and registering servers. To view registered
servers, click the VIEW tab ->Register servers. This feature allows
developers to register servers that are running older versions of SQL Server.
Registered servers have three server groups, namely: Database Engine,
Analysis Services, and Reporting Services and Integration Services. This
feature mainly allows DBAs who are running many servers to manage their
servers efficiently. In order to register a server or group of servers, you need
to have administrative privileges on the machine you are working on. Under
Register Servers ->right-click on Local Server Groups-> choose Register
Server or New Server registration for a single server. You can learn more
about this feature in due course.
The backup and restore times will depend on the network and bandwidth.
A backup file has a limitation of 1 TB.
To back up databases from earlier versions than SQL Server 2012, a tool
called “Microsoft Backup to Microsoft Azure Tool” can be used.
Some of the new features were present in SQL Server 2012 but have been
enhanced in this new release of SQL Server. There are other new features that
are not relevant to this course and therefore will not be discussed here.
Required reading
Primary data files (.mdf) are the first files created in a database and can
contain user-defined objects as well as system tables. The primary data file
also contains the links to all secondary data files and log files. According to
Microsoft, most databases will work very well with only a single primary data
file and log file. The only reason to use multiple secondary files and file group
is to obtain specific performance gains on servers with multiple physical disks.
If the database becomes too big or the first hard disk runs out of space,
secondary data files (.ndf) can be created to spread data over multiple disks.
When using multiple data files, Microsoft recommends that the primary data
file should not contain any user data and that you should preferably store all
user data in the secondary data files. Secondary files can be grouped together
into file groups. Whereas database files are the actual physical files, file groups
are logical groups of the database files. Any object in a database can be
created on a specific file group. By creating a file group on a specific database
file, you can control which objects are written to specific physical disks. This
enables you to spread the load of data access across multiple physical disks,
which can enhance performance.
Transaction log files (.ldf) do not actually contain any objects. To understand
transaction log files, you should understand how SQL Server writes data to
disk. When a user wants to make changes to data in a table, SQL Server does
not write that change directly to the data file. What actually happens is that
the data to be modified is extracted and placed in memory. Approximately
every five minutes, SQL Server takes all the changes in memory and writes
them to the transaction log file. Then SQL Server writes the changes to the
database file. This is known as a write-ahead log because SQL Server writes to
the log file before it writes to the database file.
The following is an overview of how SQL Server uses the transaction log:
4. The SQL Server CHECKPOINT process looks at the database very frequently
and flushes any modified pages in memory to the disk. CHECKPOINT marks
the transaction log to indicate which transaction was last written to disk. In
the event of a system failure, SQL Server performs automatic recovery on
startup. SQL Server looks at the transaction log after the last CHECKPOINT
because those are database changes that have not yet been written to disk.
There are two reasons for writing to a log file first. Firstly, memory is about
100 times faster than hard disk, so if the data is read off the disk and all the
changes are made in memory, the changes occur about 100 times faster. The
second reason is for recoverability. Suppose that your hard disk containing the
data fails. If you were not using a transaction log, you would lose all the
changes that were made since the last backup. However, if you have your log
file (which should be on a separate disk), you can recover all the data right up
to the moment of the failure.
NOTE
Non-logged operations operate significantly faster than logged operations
because there is no additional overhead of writing log records. Non-logged
operations are usually used for handling large amounts (in bulks) of data at
one time. This means that the transaction log is useless for database
recovery. Therefore, the database should be backed up fully before and
after performing a non-logged operation.
2.2 Transact-SQL
Transact-SQL or T-SQL is the term used for the extended SQL language in
SQL Server. This language is used to create, update, insert into, query from
and delete databases on the server. T-SQL also provides error and exception
handling. You will be working with this language and should be familiar with it
by the end of this course. Help on the syntax of T-SQL can be found either in
Books Online or in other resources that are offered by Microsoft. The syntax is
included in this guide, but it is a simplified version, and you may need to look
up the more complex syntax when going into more depth.
The client program that is used to connect to the SQL Server is called the
Microsoft SQL Server Management Studio which runs in the .NET environment.
It is compliant with any other .NET programs, meaning that it is easily
integrated with programming languages such as C# and VB.
NOTE
For those of you who are upgrading from SQL Server 2008: the Microsoft
SQL Server Management Studio replaces the Enterprise Manager, Query
Analyser and the Profiler, combining them all into one program.
Click on Start > All Programs > Microsoft SQL Server 2014 > SQL
Server 2014 Management Studio
This will open up the client application. A pane that asks which server you
would like to connect to will be presented, as shown in
Figure 11 – Connect to Server.
Server type – This gives the option of what type of server you would like
to connect to. Database Engine is the only one that will be used in this
course.
Server name – This is the name of the server that you are going to
connect to. If the down arrow is clicked, a list of the local servers that are
running on your PC will be shown. If you click on <Browse for more...>,
you will get a screen with two tabs, one being the list of local servers and
the other network servers. Connecting to network servers is very useful
because many computers can be connected to one SQL Server, making a
central database.
Click the Connect button to connect to the server that has been selected (you
should select your local server in this case). If you are unsure of what the local
server name is, type (local) in the Server name box. This will automatically
detect the local server and connect to it.
Once inside the SQL Server Management Studio, you will see something similar
to Figure 12 – Microsoft SQL Server Management Studio. Labels are inserted to
help you to understand what the different sections are for.
1. Object Explorer – This is where you can see and manage all the
databases running on the server. This means that you can also create, edit
and delete these databases using the mouse. You can also review security
settings and other useful options that SQL Server offers.
2. Output pane – All the output of the SQL Server is displayed here, whether
it is queries, printouts or error messages.
3. Code area – This area is used to type your code for creating new queries.
Any T-SQL code that you will use will be inside this query pane. To create a
new query, click on the New Query button on the taskbar at the top left.
The above is the syntax that will be used most of the time, but, if you were to
go into more depth, the following is the full syntax to create a database:
<filespec> ::=
[PRIMARY]
( [NAME = logical_file_name,]
FILENAME = 'os_file_name '
[, SIZE = size]
[, MAXSIZE = { max_size | UNLIMITED }]
[, FILEGROWTH = growth_increment]
) [,...n ]
<filegroup> ::=
FILEGROUP filegroup_name < filespec > [,...n]
NOTE
The square brackets [] are primarily used to determine identifiers. This is
necessary if the column name uses reserved keywords or contains special
characters such as space or hyphen. It is a good practice not to include
any spaces when naming columns, tables or a database.
Every database has at least two files – a primary file and a transaction log file.
Although os_file_name can be any valid operating system file name, the
name more clearly reflects the purpose of the file if the recommended file
extensions are used, as listed in Table 3 - File types.
1 USE master
2 GO
3
4 CREATE DATABASE lead_by_example
5 ON PRIMARY
6 (
7 NAME = 'lead_by_example_data',
8 FILENAME = 'c:\sql2014\lead_by_example_data.mdf',
9 SIZE = 5MB,
10 FILEGROWTH = 10%
11 )
12 LOG ON
13 (
14 NAME = 'lead_by_example_log',
15 FILENAME = 'c:\sql2014\lead_by_example_log.ldf',
16 SIZE = 5MB,
17 FILEGROWTH = 10%
18 )
19 GO
Line 1 is the USE command. This will be explained in detail later in the course.
It ensures that the master database is used. Only the master database has
permission to allow the CREATE DATABASE statement.
Line 4 contains the CREATE command along with what needs to be created, in
this case DATABASE. The name of the database is then defined (in the
database list).
Line 5 is the declaration of the primary data file that the database uses.
Line 6 contains an open bracket showing that it is the beginning of the file
specifications for the primary data file. Every opening bracket must have a
corresponding closing bracket.
Line 7 declares the name of the primary data file for referencing purposes.
Line 8 declares the file name for the primary data file that is stored on your
drive.
Line 12 declares that the log file is being created and the file specifications will
follow. The same rules apply to the log file as to the primary data file.
NOTE
The directory (‘c:\sql2014\’ in this case) must exist before you run your
script file, otherwise it will fail because it will not be able to find the
specified folder.
USE master
ALTER DATABASE lead_by_example
MODIFY Name = SuperStore; --this will be new database name
GO
Unless the database’s AUTOGROW feature is turned off, the database files will
grow automatically until disk space runs out.
1 USE master
2 GO
3
4 ALTER DATABASE lead_by_example
5 ADD FILEGROUP custom_filegroup
6 GO
7
8 ALTER DATABASE lead_by_example
9 ADD FILE
10 (
11 NAME = custom_file,
12 FILENAME = 'c:\sql2014\custom_filegroup.ndf',
13 SIZE = 5MB
14 )
15 TO FILEGROUP custom_filegroup
16 GO
17
18 ALTER DATABASE lead_by_example
19 MODIFY FILEGROUP custom_filegroup DEFAULT
20 GO
Line 15 tells the compiler that the file created must be added to the
custom_filegroup file group.
Line 19 modifies the file group to make it the default file group (a file group
cannot be modified if it does not contain files).
2.3 GO statements
The GO statement is responsible for separating sections of code. When your
code will not run or compile, the error will point to the first line of every
section. This means that if no GO statements are put in a piece of code, all the
errors will point to line 1, and you will have no idea what is causing the error.
Certain statements require GO statements after them, but the rest is up to the
programmer.
Section of code
GO
Section of code
GO
Section of code
You will be using the GO statement often in this course and it will become
easier to know where to separate the code as you go along. A basic rule of
thumb is that code that does the same thing must be grouped together, e.g.
all the code inserting into the table ‘Person’ would be in a group and therefore
have no GO statements between it. A GO statement must always appear on its
own line.
USE database_name
GO
You should see a large window open up where you can type T-SQL. Type the
following:
USE master
GO
The blue tick on the toolbar is a Parse button. It checks for potential errors in
your code before compiling it. Click it, wait a few seconds, and you will see a
message at the bottom saying that your query compiled successfully. If not,
you have mis-typed something. If the parse gave no errors, click the Execute
button to compile your code. This should also display no errors. If no errors are
displayed, you have officially created your own database. To see your
database, click on the plus (+) sign next to Databases on your Object
Explorer.
You should see your database lead_by_example listed there; if not, refresh
the Object Explorer. At this stage, this database is empty, but tables will be
added later. You will now add your own file group and add a file to it. Continue
writing in the same script file. Type the following after you have created your
database:
NOTE
The employers_filegroup was not modified to be the default file group.
You will see how to add objects to a file group manually later in this course
(if a file group is the default file group, then objects are added to it
automatically).
SQL Server has several built-in data types. Data types are used to define:
NOTE
Unicode characters are non-English characters, such as Chinese or Arabic.
Unicode characters are twice the size of standard characters.
Different data types have different memory usage. When selecting which data
type to use, rather choose the more efficient one than the largest one. This
this plays an important role in keeping large databases running smoothly and
efficiently. For example, if you wanted to have someone’s name as a column,
varchar would be a better data type than text, because it is very unlikely that
someone will have a name over 8 000 characters long, and the varchar data
type uses far less memory than the text data type. If, however, you were
going to have an essay column (very unlikely), you would have to use the text
data type because 8 000 characters would not be enough. The same applies to
all the data types; for example, smallint is a lot more efficient than real or
float.
<column_definition> ::=
column_name <data_type>
[ COLLATE collation_name ]
[ GENERATED ALWAYS AS ROW { START | END } [ HIDDEN ] ]
[ NULL | NOT NULL ]
[
[ CONSTRAINT constraint_name ] DEFAULT
memory_optimized_constant_expression ]
| [ IDENTITY [ ( 1, 1 ) ]
]
[ <column_constraint> ]
[ <column_index> ]
<column_constraint> ::=
[ CONSTRAINT constraint_name ]
{ PRIMARY KEY { NONCLUSTERED HASH WITH (BUCKET_COUNT =
bucket_count) | NONCLUSTERED } }
<column_index> ::=
INDEX index_name
{ [ NONCLUSTERED ] HASH WITH (BUCKET_COUNT = bucket_count) |
[ NONCLUSTERED ] }
<table_index> ::=
INDEX index_name
{ [ NONCLUSTERED ] HASH (column [ ,... n ] ) WITH
(BUCKET_COUNT = bucket_count)
| [ NONCLUSTERED ] (column [ ASC | DESC ] [ ,... n ] )
[ ON filegroup_name | default ]
| CLUSTERED COLUMNSTORE
[ ON filegroup_name | default ]
<table_option> ::=
{
[MEMORY_OPTIMIZED = {ON | OFF}]
| [DURABILITY = {SCHEMA_ONLY | SCHEMA_AND_DATA}]
| [ SYSTEM_VERSIONING = ON [ ( HISTORY_TABLE = schema_name
. history_table_name
[, DATA_CONSISTENCY_CHECK = { ON | OFF } ] ) ] ]
1 USE lead_by_example
2 GO
3
4 CREATE TABLE campus
5 (
6 iden INT NOT NULL ,
7 cName VARCHAR(40) NOT NULL,
8 area VARCHAR(40) NULL,
9 telephone VARCHAR(40) NULL,
10 PRIMARY KEY (iden) ,-- this will be explained next
11 CONSTRAINT ConCampusID UNIQUE(iden,cName)
12 )
13 GO
Line 6 declares a column called ‘campusID’ of the INT data type and makes it
NOT NULL (mandatory).
Modifiers can include the data type of the column or its nullity. The following
(line 9) is an example of creating a foreign key:
1 USE lead_by_example
2 GO
3 CREATE TABLE student
4 (
5 StuID INT NOT NULL PRIMARY KEY,
6 fName VARCHAR(50) NOT NULL,
7 sName VARCHAR(50) NOT NULL,
8 campusID int NOT NULL,
9 CONSTRAINT FK_tempStudent FOREIGN KEY(campusID)
10 REFERENCES campus(iden)
11 ON DELETE CASCADE
12 )
13 GO
NOTE
When creating tables in SQL Server, you must create the primary key before
the foreign key that references it. The reason for this is that a column cannot
be referenced if it contains no value. Therefore, it is recommended that you
start with the most central table and work your way outwards.
2.5 Integrity
The relational model specifies two general integrity rules. They are referred to
as general rules because they apply to all databases. They are entity integrity
and referential integrity.
The entity integrity rule is very simple. It says that primary keys cannot
contain null (missing) data. The reason for this rule should be obvious. A row
in a table cannot be uniquely identified or referenced if the primary key of that
table can be null. It is important to note that this rule applies to both simple
and composite keys. For composite keys, none of the individual columns can
be null.
The referential integrity rule says that the database must not contain any
unmatched foreign key values. This implies that:
A row may not be added to a table with a foreign key unless the referenced
value exists in the referenced table.
In general, three options are available when a referenced primary key value
changes or a row is deleted. The options are:
ALTER column_name
alter_type
GO
2.5.2 Constraints
Constraints determine the way in which a column behaves. A primary key is a
type of constraint put onto a column, but many others exist. Constraints can
be added to columns when creating or altering a table. The constraints dealt
with in this course are as follows:
1 USE lead_by_example
2 GO
3
4 CREATE TABLE employee
5 (
6 empNum INT NOT NULL IDENTITY, --auto generated numbers
7 empEmail VARCHAR(30) NOT NULL,
8 empName VARCHAR(40) NOT NULL,
9 campusID INT NOT NULL REFERENCES campus(iden),
--foreign key constraint
10 CONSTRAINT emp_EMAIL_ADD UNIQUE (empEmail),
11 PRIMARY KEY(empNum)--primary key constraint
12 )
13 GO
Line 9 – This foreign key can also be created by using the CONSTRAINT
keyword.
Line 10 – This column uses the CONSTRAINT keyword and converts the
empEmail into a unique column. A name is given to the constraint for internal
referencing (emp_EMAIL_ADD). This unique constraint uses the non-clustered
option by default.
Line 11 – This uses the PRIMARY KEY constraint and it can also be created by
using the line: CONSTRAINT prKey_empNum PRIMARY KEY (empNum).
If the code compiled without any errors, four tables will have been created:
storeBranch, employee, species and pets. As you can see, the PRIMARY
NOTE
If you create or insert into tables, but the script compiles with errors, you
must always make sure that the tables are deleted before you re-run the
script. This is because the script runs the different sections individually (in
between the GO statements) and only the section with the errors will not
compile. This means that some tables could have been created and, if they
are already in existence, they cannot be overwritten. They must be deleted
before the script is run again. To delete a table you can go to the object
browser, right-click on the tables, and select Delete
Extra constraints can now be added to the tables that have been created. Look
at the following code:
USE lead_by_example
GO
This adds a unique and a primary key constraint to two of the tables. Data will
be inserted into these tables in the next unit.
DROP object_name
GO
This code first checks whether or not the database exists. If it does, it is
dropped. Placing this code directly above your CREATE DATABASE statement
lets you start fresh every time the script file is run.
/*
This is a multi-line comment that
is not processed by the compiler.
*/
The above example will compile without errors, but it is rather hard to read.
Using indention makes it far more readable.
USE master
GO
When this is executed it will print out ‘using master database’ after the
command has been completed. It will also print ‘Database print_example
created correctly’ after the whole database has been created correctly.
Required reading
USE lead_by_example
GO
Data is entered to the campus table and the student table in the
lead_by_example database. If you insert data into the table in an order
different to the existing column order, then you must give the column names
in the correct order after the table name. The values that are being inserted
have to correspond with the order that was specified. When inserting into the
campus database, the columns to be inserted into are not specified, but the
order of the data being entered must be exactly the same as the column order.
The VARCHAR data type has to be enclosed in single quotation marks, as
otherwise it will not compile. While character data types need single quotes,
NOTE
One cannot insert data that references non-existent data. Therefore, in this
case, one has to insert into the campus table before you insert into the
student table.
3.2 UPDATE
3.2.1 Difference between UPDATE and ALTER
ALTER is not the same as UPDATE. ALTER TABLE lets one add columns and
change aspects of the table design. UPDATE TABLE lets one alter the
information that is stored in the table – it does not change the design of the
table. An example would be if a woman gets married and her surname
changes. The UPDATE TABLE statement is used to change her surname in a
table.
UPDATE table_name
SET column_name = value
WHERE column_name = value
This will update one or more records already in the table. This can be made
more specific by combining more than one matching value, i.e.:
UPDATE table_name
SET column_name = value
WHERE column_name = value AND column_name = value
USE lead_by_example
GO
UPDATE student
SET fName = 'Dean'
WHERE fName = 'Deen' AND sName = 'Fuel'
GO
3.3 DELETE
3.3.1 Difference between DELETE and DROP
The DELETE statement is very different to the DROP statement because the
DELETE statement is used to remove one or more records from one or more
tables at a time, as opposed to deleting an entire object (table/view/database,
etc.). To delete from more than one table at a time, the tables must be
logically related and the JOIN statement needs to be used (see Unit 6). The
DROP statement is used to remove a table or user definition from a database
or a database itself, when a table is DROP all data, indexes, relationships,
constraints, privileges etc.
USE lead_by_example
GO
DROP table Employee;
GO
--Dropping a database
USE MASTER;
GO
DROP DATABASE lead_by_example;
GO
Criteria must be specified so that a specific row may be dropped. The more
criteria specified, the more specific it becomes, i.e. the DELETE statement will
delete every record that matches the criteria.
USE lead_by_example
GO
This will check the table campus for all records that have ‘Oompaloompa’ as a
cName value and remove them. Since there is only one record that matches
the criteria, only that one record will be removed. Use the AND operator for
multiple criteria.
NOTE
I recommend that you watch this video to learn efficient SQL rules and help
you write SQL queries more easily: WiseOwlTutorials, SQL Server Part1 –
Writing Basic Queries: here [Accessed: 21 September 2015]
USE lead_by_example
GO
When the species table was inserted into, information was not entered into
the IDENTITY column. You need an explicit statement to force data entry into
an identity column. See the following:
This forces the entry into the IDENTITY column of the table (be warned: you
have to make sure that the value you are going to insert is unique).
USE lead_by_example
GO
UPDATE species
SET speciesText = 'Lion'
WHERE speciesID = 4
GO
The table species has had its value for the speciesText changed from ‘Cat’ to
‘Lion’. A more detailed UPDATE statement using JOINs will be used in Unit 6.
Try to work out how to DELETE a record from one of your tables. The following
code shows how this is done:
USE lead_by_example
GO
This deletes the record 003, Tweebuffelsfontein, Freestate from the table
storeBranch. This is acceptable because there are no records referencing it. If
a record that is being referenced needs to be deleted, the referencing record
would need to be deleted first. This can be done easily by using the JOIN
statement (explained in Unit 6).
Required reading
Chapter 20, 21 & 23 - Microsoft SQL Server 2014 UNLEASHED.
NOTE
In this unit, a database called lead_by_example is used.
In T-SQL, the SELECT statement is used to query the database. The syntax is
as follows:
SELECT column_list
FROM table_name
This syntax is only for querying data from one table. Querying from more than
one table will be discussed at a later stage. Ensure that the database that
needs to be queried from is the one that is being used by the SQL Server
Management Studio (USE statement). The asterisk (*) can be used to select all
the columns. The syntax is as follows:
USE lead_by_example
GO
SELECT *
FROM student
GO
This retrieves every row (all of the columns) from the table student. Take
note that the lead_by_example database is being used. If this database was
not specified, it would give the error that no table by that name exists.
SELECT column_list
FROM table_name
WHERE column_name = value
GO
This will select the whole record that has the value of the specified column
equal to the value specified. An example is:
USE lead_by_example
GO
SELECT *
FROM employee
WHERE campusID = 1
GO
This retrieves all the records under employee that are at the Randburg campus
(id 1). The result is shown in Figure 14.
The LIKE command can be used if it is unclear what needs to be queried. This
is a very useful command that is easy to use:
USE lead_by_example
GO
SELECT *
FROM employee
WHERE empName LIKE '%u%'
This will select all the names that contain the letter u.
Wildcard Function
% Percentage Any number of characters
_ Underscore Any single character
[] Square brackets Single character within in a range
[^ ] A carat enclosed by square Excluding a single character within a
brackets range
When selecting, it is possible to use the OR and AND operators. Use the AND
operator to further limit the result set. The AND operator requires that all
conditions are met. The OR operator returns rows that meet any of the given
conditions. This is an example of putting columns in a custom order:
USE lead_by_example
GO
The result of the code is shown in Figure 15- Including certain columns.
Notice that it has left out the empNum and campusID columns because
those columns are not specified in the query.
See Books Online for more built-in functions. String functions, for example, can
be useful. With these functions, text data can be manipulated extensively.
USE lead_by_example
GO
CREATE TABLE products
(
productID INT NOT NULL,
productName VARCHAR(25) NOT NULL,
price MONEY NOT NULL CHECK(price>0),
proDescrp TEXT ,
CONSTRAINT products_pk PRIMARY KEY(productID)
)
GO
USE lead_by_example
GO
GO
GO
Now, this example shows the difference between when GROUP BY is used and
when it is not:
USE lead_by_example
GO
The result of this code is shown below in Figure 16 - The store names and
quantity sold.
The GROUP BY clause can now be used to add up the total qtySold for each
stor_name. See the following example:
USE lead_by_example
GO
Figure 17 GROUP BY
This may look like a very complicated query but it is a lot easier to understand
if it is broken down into simpler components. The GROUP BY clause groups the
stores together by stor_name of the stores table (specified on the last line).
The purpose is only to display each stor_name once and the SUM(sales.qty)
for each stor_name. The SUM command adds up the values that are put into
the brackets, sorted according to the GROUP BY clause, i.e. in this case, it
would add the quantities sold for each stor_name. An aggregate function such
as SUM may be accompanied by a GROUP BY clause.
The AS keyword next to the SUM function is called an alias. Aliases are used to
simplify long or complex table names or column names. It temporarily names
the column or table to the specified value - in this case, qtySold.
HAVING works in a similar manner as the WHERE clause, but HAVING can use
aggregate functions and WHERE cannot. The HAVING clause must also be
accompanied by the GROUP BY clause. The following example performs exactly
the same action as the previous query, but it uses the HAVING clause and alias
naming; the results are shown in Figure 18.
USE lead_by_example
GO
4.1.6 ORDER BY
The ORDER BY clause is very different to the GROUP BY clause. The ORDER BY
clause sorts the rows retrieved by the specified column in ascending or
descending order. Use the keyword DESC to sort the rows in descending order.
If DESC is not specified, it is set to ascending order by default.
USE lead_by_example
GO
SELECT storeName
FROM storeBranch
ORDER BY storeName DESC
GO
4.1.7 TOP N
The N in TOP N is a placeholder for a number. TOP N displays the top N of a
query. By itself, it provides no organisation and will simply search the tables
and retrieve the number of columns in the order that they are in the table.
When TOP N is combined with ORDER BY, a real representation of the top
values specified in the ORDER BY statement can be seen. See the following
example (results shown in Figure 20 TOP N).
USE lead_by_example
GO
SELECT TOP 3 storeName
Figure 20 TOP N
This has retrieved the top three records as they appear in the table. Using
ORDER BY, the query first sorts the results and then retrieves the top three
records according to stor_name (results shown in Figure 21).
USE lead_by_example
GO
SELECT TOP 3 storeName
FROM storeBranch
GO
This has sorted the results in descending (z to a) order and then retrieved the
top three.
4.1.8 DISTINCT
The DISTINCT keyword is used only if unique values need to be selected. This
means that no duplicate values will be retrieved. This is usually used with the
ORDER BY clause. As soon as the first unique record is found, it will ignore all
other records. The syntax for this is:
NOTE
Tables created with SELECT INTO do not have indexes, primary keys, foreign
keys, default values or triggers. If any of these are required, the table should
be created using the CREATE TABLE statement and then the INSERT
statement should be used to fill the table with data.
Using SELECT INTO with temporary tables is useful when a very large data set
is reduced into a smaller set. For example, you may want to select a subset of
400 rows (sorted in three different ways) from a data set of 1 000 000 rows.
You can create a temporary table with only the 400 rows that you need, and
then perform the rest of the work using the temporary table. The syntax is as
follows:
SELECT column_name(s)
INTO new_table_name
FROM old_tablename
USE lead_by_example
GO
SELECT *
INTO #tempTable
FROM employee
WHERE campusID = 1
In this example, the employees are selected from one campus and put into a
temporary table, which can be recognised by the # sign in front of the new
table name.
IF: this is one of the most frequently-used control of flow keywords. Like in
other programming languages, IF is used to test a Boolean condition. When
the result of the IF statement is True, the next proceeding line is executed.
ELSE: the ELSE keyword can be combined with IF to execute logic when the
IF statement returns False. Else is an optional statement.
USE lead_by_example
GO
IF EXISTS(SELECT name FROM Employee WHERE surname = 'Zuma')
PRINT 'Found it Zuma'
ELSE
IF EXISTS(SELECT name FROM Employee WHERE name = 'Smith')
PRINT 'Found it Smith'
ELSE
PRINT 'None is found Found Smith or Jones'
BEGIN…END: the BEGIN and END keywords are used to group multiple lines
into one statement block. An example of when statement blocks are
required is in the result of an IF ELSE statement. In this example, two
PRINT lines are wanted on True result. Nothing should be returned on a
False result.
GOTO: this defines a label and allows the code to jump to that label from
some other point. Cursors usually make use of the GOTO statement.
However, a GOTO can also be used alone.
RETURN: when the RETURN keyword is reached, statement execution ends,
unconditionally. Any lines following a RETURN are not executed.
do_it_again:
IF @Count < 100
BEGIN
PRINT ‘Counting not complete'
RETURN
SET @Count = @Count + 1
END
WHILE: WHILE creates a loop that keep on executing until a Boolean False
condition is received. Like IF statements, WHILE statements execute while
the condition is true.
One of the problems with control of flow statements is that they can be
misused and one of the common errors is a missing BEGIN and END. Since T-
SQL does not indent flow statements well, confusion can occur if great care is
not taken. Regardless of these points, well-used control of flow statements can
transform Transact SQL statements into powerful programming structures.
4.5 Shortcuts
A few shortcut keys, which you might find useful when writing queries, are
listed in Table 7 – Shortcuts.
Table 7 – Shortcuts
Required reading
Chapter 34 2, 3 & 8 - Microsoft SQL Server 2014 UNLEASHED.
5.1.1 Pages
In an SQL Server data file, pages are the smallest unit of storage. A page
belongs to a specific object. Each page starts with a page header of 96 bytes
and is 8 192 bytes (8 KB) in total. This means that each page can hold 8 096
bytes of data. Before SQL Server 7.0, a page was 2 KB. Two types of pages
will be discussed:
Data pages – These pages contain most of the data that is inserted into
tables. The only user-entered data that is not stored in a data page is text
and image data, because both are usually large enough to warrant their
own pages.
Index pages – These pages are used to accelerate data access. Indexes are
stored separately from data in their own page type.
5.1.2 Extents
To avoid fragmentation, SQL Server assigns space in extents. An extent is a
collection of eight contiguous pages (64 KB). When more space within a data
file is needed for an object, at least one full extent is allocated. Even though a
page belongs to a specific object, an extent can contain pages belonging to
many different objects.
Mixed extents are used for objects that are too small to fill eight pages by
themselves.
Clustered indexes determine the order of rows in a table. There can only be
one clustered index for each table because the rows can only be in one order.
These are used by default in a table when a primary key is created and
therefore are unique by default.
The main difference between these two indexes is that clustered indexes are
unique. Any given table can only have one clustered index. The leaf level of a
clustered index is the actual data. On the other hand, the non-clustered index
leaf level is a pointer to the data in rows; so we can have as many non-
clustered indexes as we like on a database.
In general, one should index columns that are included in the search criteria
using conditions that do not include functions or calculations.
Searchable arguments (SARGs) are the types of arguments that can be used
by SQL Server using indexes. For example, WHERE emp_lname LIKE ‘W%’
is searchable, but WHERE emp_lname LIKE ‘%w%’ is not. In the first
example, the emp_lname column is searched for values that begin with a W.
The second example searches the emp_lname column for values that contain
a W. Imagine if one tried to do a search like this in the White Pages telephone
book. The second condition would not be found easily and SQL Server would
have the same problem. Searching for only the first letter narrows the search
quite considerably.
[ ; ]
<object> ::=
{
[ database_name. [ schema_name ] . | schema_name. ]
table_or_view_name
}
NOTE
SQL Server has a data structure called b-tree that keeps data sorted for
easy searching. Indexes are organised as B-trees, and each page in the
index is called an index node. The bottom level nodes are called leaf nodes,
while the top level is called the root node.
The following options are not all the options that are available. See Books
Online for more options.
IGNORE_DUP_KEY is used for ignoring the error that the table will throw when
a value that needs to be unique conflicts with another. The table will give a
warning and continue, not inserting that row. If this option is not specified, the
whole statement will crash.
Use lead_by_example
GO
This will create a non-clustered index on the column empEmail in the table
employee. If clustered is not mentioned, the compiler automatically uses a
non-clustered index. The reason behind this is that a clustered index defaults
to the primary key column.
It is possible to create a composite index (an index made up of more than one
column). This is used when one column is not unique enough for a clustered
index. An example would be to combine a name and a surname into one index.
If a composite index is created, all that needs to be done is to separate the two
columns inside the brackets with a comma.
USE lead_by_example
GO
-- Create a table if you do not have an existing table.
To add a filter to an index using T-SQL, open Query Editor in SQL Server
Management Studio and type the following T-SQL code:
ON exams
examDate(courseId, examNumber)
WHERE(OnlineExamFlag=0)
WITH(DROP_EXISTING = ON);
When an index is disabled or dropped, the table name that the index is
attached to needs to be specified. This can be done as follows:
This will drop the index that was created earlier on the exams table.
USE lead_by_example
GO
a) 2 KB
b) 8 KB
c) 64 KB
d) 128 KB
5. Indexes can be categorised into two primary types. What are these types?
8. With the use of T-SQL code, demonstrate the process of disabling and
deleting an index.
Required reading
Chapter 22, 3 & 8 - Microsoft SQL Server 2014 UNLEASHED.
Join tables.
Create subqueries.
Create views.
INNER JOIN
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
CROSS JOIN
SELECT column_list
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name = table_name2.column_name
UPDATE table_name
WHERE column_name
INNER JOIN table_name2
ON table_name1.column_name = table_name2.column_name
SELECT column_list
FROM table_name1
OUTER_JOIN_TYPE table_name2
ON table_name1.column_name = table_name2.column_name
SELECT column_list
FROM table_name1
CROSS JOIN table_name2
INNER JOIN is the most common join and will be used most often in this
course.
NOTE
Since more than one table is involved in JOIN statements, the table name
needs to be specified before each column; otherwise, the compiler will not
know which table the column belongs to. This only applies to columns that
have the same name, but it is good practice to do it for all columns, i.e.
table_name.column_name
Line 6 shows that an INNER JOIN is being used. Note that only the word JOIN
is used and SQL Server automatically assumes it to be an INNER JOIN. The
second (right) table that is involved in the JOIN is also mentioned here.
Line 7 specifies where the two tables must be joined. The student.campusID
is the foreign key in the table student. This is linked to the campus.iden,
which is the primary key in the table campus. Note that the JOIN does not
have to be the same as the relational link of the two tables, but it is most often
like that.
Four records are retrieved. The first column is the student name and the last
column is the campus name from the campus table. The link is the campusID
in both tables.
6.2 Sub-queries
6.2.1 Normal sub-queries
A SELECT statement nested inside another SELECT statement is commonly
referred to as a subquery. A subquery can produce the same results as a JOIN
operation and is always enclosed within parentheses. Most SELECT statements
that have been used so far have retrieved data from individual tables.
Each step can be executed as a single query by using the results returned from
one SELECT statement to populate the WHERE clause of the next SELECT
statement, or both queries can be combined into a single statement. See the
following example:
USE lead_by_example
GO
The above code retrieves the employees from the campuses that have
students named Dean. This can be adapted in any way. Try to experiment with
it in order to familiarise yourself with the syntax.
6.3 Views
Views can be thought of as virtual tables or stored SELECT statements. The
only difference between a view and a select statement is that a view does not
actually contain any values. The values that appear to be in a view are actually
pointers to the real values in a table or tables. In other words, when the value
in the table is changed, the values in the view referencing it will also change.
The same thing is true if the values in a view are changed because the values
in the table are actually changed.
attribute ::=
{ENCRYPTION | SCHEMABINDING}
Attribute Description
Encrypts the CREATE VIEW statement in the syscomments
system table. Once a view definition is encrypted, it
Encryption
cannot be seen by anyone (even the view owner) and the
only way to decrypt it is to drop the view and recreate it.
The SCHEMABINDING attribute forces one to use two-part
names (owner.object) to refer to the base tables
Schemabinding referenced in your view’s SELECT statement. When this is
done, the schema of the base table cannot be changed or
dropped unless the view is dropped or altered.
USE lead_by_example
GO
This creates a view that will contain all the last names of the employees and
the corresponding campuses. To see this, query everything from the view:
USE lead_by_example
GO
This should retrieve all the rows of the view, as shown in Figure 25 –
vw_Example.
An advantage of this is that one can specify exactly what certain people are
allowed to access. Limiting the number of people who have access to the
database directly helps protect data against data redundancy and
inconsistencies.
USE lead_by_example
GO
This script creates a view that will select every pet and show what species it is,
also including the store at which it is available. It then queries the whole view.
The output is shown in Figure 26 – vw_firstView.
Figure 26 – vw_firstView
Next, insert data into the tables that you created earlier. Feel free to add
your own records. Remember that you cannot insert into a foreign key
column unless there is already data in its referenced primary key.
INSERT client
VALUES ('John Doe', ' 20 Small Str', '535-6548'),
('Sipho Gumede', '14 E Ville', '555-7548'),
('John Claw', ' 19 Ellof Str', '555-6785'),
('Musa Ndaba', '13 DM Ville', '555-4532'),
('Thuli Gumede', '12 Mandela drive', '555-2467'),
('Jonas Ntlapo', '09 Sisulu Str', '555-4761'),
('Jimmy Dludlu', ' 18 Walker street', '555-3479')
GO
Using the sample data you inserted, create a view that will find all items
that are equal to, or under, their reorder levels. The view must return the
stockID, stockName, StockLevel and MaxLevel.
Using the view you created, create a stored procedure that will restock all the
items in the stock table that need reordering by 4 units more than the
maximum level of each item. So, if the current stock level of a certain item is
3, and the reorder level is 10, then the new stock level must be 14.
The new stock level must be 14 after the procedure has run successfully.
Required reading
Chapter 24 - Microsoft SQL Server 2014 UNLEASHED.
User defined
System
Temporary and extended user-defined
This will create a stored procedure that retrieves a simple query. Once created,
it may be executed using the EXEC keyword:
USE lead_by_example
GO
EXEC spSimple
This will execute the stored procedure that was created. It should give the
same results of the processing that the stored procedure did (see Figure 27 –
Results of spSimple).
7.1.2 Groups
After the procedure name, there is an option to specify the procedure’s
number. This is used when procedures need to be in a group. All the stored
procedures in a group are given the same name but a different number must
be given for each. See the following example:
USE lead_by_example
GO
In the simple stored procedure that was created earlier, a simple SELECT
statement was used. No matter how many times the procedure is executed, it
will always produce the same output. If a stored procedure needed to process
different information depending on the situation, the stored procedure would
require input. Parameters are used for this purpose. When specifying
parameters in a stored procedure, the @ symbol must be used because a
parameter is a type of variable and needs to be stored in memory temporarily.
See the following example:
USE lead_by_example
GO
This example makes use of parameters and is quite a simple example that
does not need any extra variables declared within it. The parameters are three
numbers – two for input and one for output. Values need to be supplied to
execute this stored procedure:
In this execution, two numbers are supplied for input and one local variable for
output. The variable has been declared beforehand as an integer. It is
necessary to use a variable here because that value is used later in the print
statement. When the execute statement is run, 6 is returned as the value of
the variable @ans.
7.1.4 Validation
Validation plays an important role in SQL Server. Validation refers to checking
whether the values about to be processed are valid according to the
requirements. An IF statement can be used to check whether a condition is
true or not. Use the BEGIN and END keywords if you want more than one thing
to happen if the condition is met. A WHILE loop will execute if a condition is
met and will repeat the code until the condition is not met.
For example, to calculate the randdollar exchange rate, the number entered
must be positive:
USE lead_by_example
GO
IF(@Dollars<0)
BEGIN
RAISERROR('You cannot enter a negative value for
Dollars',16,1)
RETURN
END
NOTE
The difference between results and output is that results return values in
table format. Output shows the print statements, warnings and errors in text
format.
Variable Description
Returns the number of successful and non-
@@CONNECTIONS
successful logins since the start of the server.
Returns the error code for the last T-SQL
@@ERROR
statement that was executed.
Returns the last value that was inserted into a
@@IDENTITY
column with the IDENTITY property.
Returns the number of rows that were affected
@@ROWCOUNT
by the last T-SQL statement executed.
Returns information about the current instance of
@@SERVERNAME
SQL Server that is running.
Returns the current version of the database
@@VERSION
software.
Contains the number of active transactions for
@@TRANCOUNT
the current user.
Returns a code used in a cursor to check whether
or not fetching a row of data was successful. The
@@FETCH_STATUS
codes are:
0 – no error
USE Lead_by_example
GO
This function returns a table. This means that when it is called, it should be
part of a query:
USE Lead_by_example
GO
This will call the function and select what is specified from the table that is
returned. To create a function that returns a scalar value is quite simple. See
the following code:
RETURN @num
END
GO
This function simply adds up all the royalties of all the authors (using the
previous user-defined function). The variable is needed to store an integer
value from the table, and then return the value. A mere SELECT statement
cannot be returned because it will return a temporary table, and this is not
what was specified.
7.3 Iteration
SQL is a set-based language, meaning that it retrieves sets of data. This is
what makes it so different from other languages. Sometimes you need to
iterate through the rows in a table. This is very important when you need to
print a report for each row - for example, a list of all users with their details.
Use a standard WHILE loop and assign a new column to a table to show if that
row has been processed or not. See the following example:
USE lead_by_example
GO
UPDATE #tempEmp
SET Printed = 1
WHERE @ID = empNum
END
GO
As long as there are rows that have the column Printed equal to 0, the code
inside the loop will repeat. The first statement in the loop sets the variable
@ID to the lowest primary key that has its Printed value equal to 0. One may
think that this is a useless statement because the empNum column increases
in ascending order (1, 2, 3, 4, etc.), but most of the time the primary key
column is not consistent (e.g. 1, 3, 5, 8, 9). This statement is prepared for any
situation.
Database Management Study Guide | V1.1 November 2015 Page 100 of 168
Now that the variable @ID has been given a value; the whole row is selected,
including the campus name that the employee belongs to. The values from
each column in that row are assigned to the variables that were declared
earlier.
The last step is to print out the information in a formal manner and finally
change the value of Printed to 1 to indicate that it has been printed and does
not need to be read again. The next time the @ID variable is set to the lowest
primary key, it will exclude this row.
7.4 Cursors
Cursors allow you to work with data iteratively (one row at a time), rather than
in sets. Traditionally, SQL is a set-based language. For example, when you
execute a SELECT statement, it returns a set of rows. The most fundamental
data manipulation statements (SELECT, UPDATE, INSERT and DELETE)
normally work with entire sets of data at a time. Cursors enable you to define
a set of data and work with that data one row at a time. To work with data in
this way, you generally need to use some form of a loop to iterate through the
set, which is why using cursors is called an iterative approach. A cursor is a set
of rows together with a pointer that identifies a current row.
SQL Server can work with data as a set faster than with an iterative series of
commands. Most iterative solutions can be expressed as a set; therefore,
cursors should be avoided. Thinking in terms of whole sets of data is what
makes Structured Query Language so different from traditional programming
languages.
There are two ways to declare a cursor: you can use a syntax based on the
ANSI SQL standard or an extended syntax which is not ANSI SQL-compatible.
The ANSI SQL syntax for declaring a cursor (as specified in SQL Server Books
Online) is as follows:
Database Management Study Guide | V1.1 November 2015 Page 101 of 168
NOTE
If the SCROLL option is not used, the cursor only positions itself one row at a
time in the forward direction. This is known as a forward-only cursor.
Because positioning in this situation is so predictable, no keysets need to be
created and stored in tempdb, allowing the cursor to be opened more quickly
and positioning speed to be much faster. The predictability of scrolling through
a forward-only cursor is also why such a cursor can be updateable even if no
unique indexes are available.
The system database tempdb is a global resource where temporary tables and
other values are stored. Data is stored per user per session, so that any
number of users may, for example, create a table called #tempTable, each
instance of which will be visible only to the user who created it. A user’s
temporary tables and other data in tempdb are lost when that user’s session
ends.
This is the extended syntax for declaring a cursor (as specified in SQL Server
Books Online):
The DECLARE command does all the work of defining a cursor, but it does not
actually create a cursor as an object that can be used. The cursor is not
created until it is opened with the OPEN command. The OPEN command
requires only the name of the cursor:
When the cursor is opened, the SELECT statement in the DECLARE command is
executed and any results needed for the cursor are collected. If the cursor is
INSENSITIVE, all rows are collected and stored in tempdb, ensuring that the
data remains unchanged from when the cursor is first opened. If the cursor is
FORWARD-ONLY, almost no information is collected. The OPEN command does
not implicitly perform an initial FETCH on the data. Once a cursor has been
opened, you can use the @@CURSOR_ROWS global variable to retrieve the
number of rows in the cursor.
Database Management Study Guide | V1.1 November 2015 Page 102 of 168
The FETCH command retrieves requested rows from the cursor’s result set.
The data from these rows can be stored in variables specified in the FETCH
command. The syntax is as follows (as specified in SQL Server Books Online):
For a complete listing of keywords and their explanations, refer to the section
FETCH in SQL Server Books Online.
The CLOSE and DEALLOCATE commands take the cursor name as their only
parameter. The CLOSE command releases any data being held by the cursor
since it was opened. No further positioning or editing can be done on a closed
cursor. The DEALLOCATE command removes the definition of the cursor from
the server’s memory. After a DEALLOCATE command, the cursor cannot be
reopened.
Here is an example of how a cursor would be declared and used. Please note
that in order for this code to compile and run successfully, the necessary
tables, columns and constraints need to be in place.
Database Management Study Guide | V1.1 November 2015 Page 103 of 168
CREATE PROCEDURE sp_OrderDetails
@orderID INT
AS
BEGIN
DECLARE @custNumber INT
DECLARE @custName VARCHAR(30)
DECLARE @orderDate SMALLDATETIME
DECLARE @orderTotal SMALLMONEY
DECLARE @productName VARCHAR(100)
DECLARE @productPrice SMALLMONEY
DECLARE @quantity SMALLINT
DECLARE detailCursor CURSOR
FOR SELECT Products.ProdName, Products.Price,
OrderDetails.Quantity
FROM Products
INNER JOIN OrderDetails ON OrderDetails.ProductID =
Products.ProductID
INNER JOIN Orders ON Orders.OrderID = OrderDetails.OrderID
WHERE Orders.OrderID = @orderID
FOR READ ONLY
SET @orderTotal = 0
SELECT @custNumber = Customer.CustID, @custName =
Customers.CustName,
@orderDate = ISNULL(Orders.OrderDate, GETDATE())
FROM Orders
INNER JOIN Customers ON Customers.CustID = Orders.CustID
WHERE Orders.OrderID = @orderID
OPEN detailCursor
FETCH FROM detailCursor INTO @productName, @productPrice,
@quantity
Database Management Study Guide | V1.1 November 2015 Page 104 of 168
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @productName + ' @ R' + CONVERT(VARCHAR, @productPrice)
+ ' x ' +
CONVERT(VARCHAR, @quantity)
SET @orderTotal = @orderTotal + (@productPrice * @quantity)
FETCH FROM detailCursor INTO @productName, @productPrice,
@quantity
END
PRINT ' '
PRINT 'Order Total : R' + CONVERT(VARCHAR, @orderTotal)
CLOSE detailCursor
DEALLOCATE detailCursor
END
Function Description
LOWER(char_expr) Converts char_expr to lowercase.
Converts char_expr to
UPPER(char_expr)
uppercase.
Returns the number of characters
LEN(string_expr) of the specified string expression,
excluding trailing blanks.
Returns data without leading
LTRIM(char_expr)
blanks.
Returns data without trailing
RTRIM(char_expr)
blanks.
Returns the starting position of
PATINDEX('%pattern%', expression) the first occurrence of a pattern
in the specified expression.
Everywhere that string2 appears
REPLACE('string1', 'string2', 'string3') in string1 it is replaced with
string3.
REPLICATE(char_expr, no) Repeats char_expr no. times.
REVERSE(char_expr) Returns the reverse of char_expr.
Database Management Study Guide | V1.1 November 2015 Page 105 of 168
Returns part of a character or
SUBSTRING(expression, start, length)
binary string.
The following are some examples of how to use these string functions:
DECLARE @x VARCHAR(30)
Normal:
Hello, my name is Death.
Upper case:
Database Management Study Guide | V1.1 November 2015 Page 106 of 168
HELLO, MY NAME IS DEATH.
Lower case:
hello, my name is death.
Use of substring:
is Death
Combining these string functions together can greatly improve how the text
looks. The CAST() function in the above example converts from one data type
to another. This CAST converts the result of PATINDEX () from an INT to a
VARCHAR.
The REPLICATE and LEN functions are very useful together when used to print
out a list of items. This will ensure that all values are aligned one below the
other.
There is another way to improve the output of text when using iteration. The
line (n row(s) affected) that appears in the output of the iteration can be
removed. This line can get in the way and make things look unprofessional.
The following command will tell the compiler to not print this line:
SET NOCOUNT ON
GO
The line can be inserted just before the CREATE PROCEDURE statement.
Database Management Study Guide | V1.1 November 2015 Page 107 of 168
Table 11 - Useful date functions
Function Description
DAY(date) Returns an integer value representing the day.
MONTH(date) Returns an integer value representing the month.
YEAR(date) Returns an integer value representing the year.
GETDATE() Returns the current date and time.
DECLARE @y DATE
SET @y = GETDATE()
Normal: 2013-09-06
Day: 6
Month: 9
Year: 2013
There are a few more things that can be done with string and date functions
and you are encouraged to do more research into this.
Required reading
Chapter 25, 26 & 28 - Microsoft SQL Server 2014 UNLEASHED.
Database Management Study Guide | V1.1 November 2015 Page 108 of 168
Unit 8 – Triggers, Transactions
Create a trigger.
Understand how triggers work.
8.1 Triggers
Triggers enable you to ensure data integrity, domain integrity and referential
integrity. There are several rules about how and when they should be created.
For example, they can be used for validation purposes.
Triggers have relatively low overheads. Referencing other tables uses up most
of the time involved in running a trigger. Referencing is fast if the other tables
are in memory or a bit slower if they must be read from a disk. Triggers are
always considered a part of the transaction. If the trigger or any other part of
the transaction fails, it is rolled back.
DML trigger
DDL trigger: This type of trigger is fired against DDL statements like Drop
Table, Create Table or Alter Table. DDL Triggers are always after Triggers.
Logon trigger: This type of trigger is fired against a LOGON event before a
user session is established to the SQL Server.
Database Management Study Guide | V1.1 November 2015 Page 109 of 168
Triggers use the inserted and deleted tables, both of which contain the same
structure as the base table where the trigger was created. These tables reside
in RAM because they are logical tables.
The trigger can be set up on a table or a view, meaning that when the user
performs an action specified in this trigger, the trigger will fire.
There are various uses of triggers. The first is the FOR, AFTER and INSTEAD
OF options. These will specify when the code will be executed once the trigger
has been fired. Using the FOR option specifies that something will happen
before the event that fired the trigger. The AFTER option specifies that the
code will execute after the event that fired the trigger. The INSTEAD OF option
will not let the event happen but will do whatever is specified instead.
The INSERT, UPDATE and DELETE options are used for specifying when the
trigger will fire, i.e. if the INSERT option is used, the trigger will fire when data
is inserted into the specified table or view.
AS specifies that the next SQL statement is to be executed when the trigger is
fired, for example:
USE lead_by_example
GO
Database Management Study Guide | V1.1 November 2015 Page 110 of 168
This code creates a trigger that is set up to fire when someone attempts to
insert data into the table campus. When the trigger fires it will print out a
message instead of inserting data.
Directly after the trigger, an attempt to test this trigger is done by inserting a
new row into the table campus. When this code is executed, the following
should be printed out:
(1 row(s) affected)
When the information in table campus is checked, the information from the
test will not be there.
USE lead_by_example
GO
Database Management Study Guide | V1.1 November 2015 Page 111 of 168
This code creates two triggers, i.e. tr_notify and tr_edit_store. The first one
prints out a notification that inserting into the table employee was a success.
The second one is fired when someone tries to insert into, delete from or
update the storeBranch table. It will first throw a custom error using the
RAISERROR keyword and then insert into the table errors. This table was
created to store types of errors that occur during the lifetime of the database.
The GETDATE function is cast into a varchar when it is inserted into the errors
table.
USE lead_by_example
GO
(1 row(s) affected)
(1 row(s) affected)
Employee inserted successfully
(1 row(s) affected)
You can see the triggers taking effect here when they display the messages
that you specified.
8.2 Transactions
A transaction is one or more SQL statements that must be completed as a unit
of work. Transactions provide a way of collecting and associating multiple
actions into a single all-or-nothing, multiple-operation action. All operations in
transitions must be fully completed or not performed at all. Consider an
example of a bank transaction in which the customer transfers R500 from a
cheque account to a savings account. This transaction has two operations: a
decrement of cheque account and an increment of savings account. What if the
bank server went down after completing the first step and never went to the
Database Management Study Guide | V1.1 November 2015 Page 112 of 168
second? When the two operations are combined as a transaction, they either
both succeed or both fail as a single complete unit of work.
SQL Server 2014 comes with the ability to reduce transaction latency by
designing some or all transactions as delayed durable. A delayed durable
transaction (lazy commit) returns control to the client before the transaction
log record is written to disk. Fully durable transactions return control to the
client only after the log records for the transactions are written to disk. This is
default transaction behaviour in SQL Server.
Atomicity: ensures that all operations within the work unit are completed
successfully; alternatively, the transaction is aborted at the point of failure,
and previous operations are rolled back to their former state.
Consistency: guarantees the stated change of database after a successful
transaction.
Isolation: allows transactions to operate independently of, and transparently
to, each other.
Durability: ensures that the result or effect of a committed transaction
remains in case there is a system failure.
Database Management Study Guide | V1.1 November 2015 Page 113 of 168
SAVEPOINT: creates points within groups of transactions in which to
ROLLBACK.
SET TRANSACTION: places a name on a transaction.
Employee table
ID Name Age Address Salary
1 Eddie 33 18 Albert Street 20000
2 Jan 41 91 Albertina Sisulu Street 60000
3 Peter 35 12 Lilia Ngoyi Street 34000
4 John 22 15 Pretorius Street 800
5 Sipho 25 21 William Nicol Drive 20000
USE lead_by_example
GO
BEGIN TRAN
UPDATE Employee
SET Name = 'John'
WHERE iden= '321'
UPDATE Employee
SET Name = 'JohnY'
WHERE city = 'Johannesburg'
IF @@ROWCOUNT = 5
COMMIT TRAN
ELSE
ROLLBACK TRAN
USE lead_by_example
GO
BEGIN TRANSACTION
GO
DELETE FROM Employee
WHERE Age = 35;
GO
SAVEPOINT TRANSACTION;
GO
Database Management Study Guide | V1.1 November 2015 Page 114 of 168
4. The SET TRANSACTION syntax:
Example:
USE lead_by_example
GO
SET TRAN READ ONLY NAME ‘John’;
COMMIT;
Required reading
Chapter 27 - Microsoft SQL Server 2014 UNLEASHED.
Database Management Study Guide | V1.1 November 2015 Page 115 of 168
Unit 9 – Database Administration and Security
Integrated security enables users to use the network login and password
supplied to Microsoft Windows NT as a security mechanism to access their data
server. Once user validity with a login and password is verified by Microsoft
Windows NT, the user can connect to the server. Keep in mind that connecting
to the server does not mean the user has access to the database.
Mixed security is useful when users need to supply only one login and
password to be on the network and connect to the server. This method is
popular in today’s business of mixed legacy environments.
Our main focus in this section will be on the standard security setting.
The previous releases of SQL Server had server logins mapped to users, but
SQL Server 2014 has an alternative connection method with the concept of
contained databases. This will be discussed later on in this unit.
Roles make administration much easier because one does not have to set
permissions for every user. Users can belong to more than one role. The four
types of server roles are:
Fixed server
Fixed database
Public database role
User-defined database
Database Management Study Guide | V1.1 November 2015 Page 116 of 168
All users in the database belong to that database’s public role. If all members
of that database need to share the same permissions, the permissions can be
assigned to the public database role. Fixed server, fixed database and public
roles are built-in roles and cannot be dropped.
Database Management Study Guide | V1.1 November 2015 Page 117 of 168
database object.
9.2.4 Schemas
Schemas are used for defining what any given user owns (grouped together).
You may have noticed during the course that there was occasionally an owner
specified as a prefix to objects in the database, e.g. dbo.table_name. This is
the schema to which that object belongs.
A default schema is set to a database, meaning that the database engine uses
this first when resolving object names in that database. The three types of
default schemas that exist are:
Database Management Study Guide | V1.1 November 2015 Page 118 of 168
BACKUP DATABASE can be granted to logins. By default the server login
principal is created during SQL Server installation.
Database Management Study Guide | V1.1 November 2015 Page 119 of 168
Figure 30 – Windows Login Authentication
On the default language drop-down list, you can leave the language as
default or you can select the language of preference.
Now select Server Roles on the Select a page pane. On the listed Server
Roles, select sysadmin which allows the system administrator to execute
any task on the server, since public is selected already.
NOTE
The sysadmin role has unrestricted permissions to all databases without the
need to create database users. Therefore, it is important to consider who to
grant this role to.
If your machine is not connected to any domain, the username or name of the
PC will work fine.
Database Management Study Guide | V1.1 November 2015 Page 120 of 168
Figure 31 – SQL Server Roles
Database Management Study Guide | V1.1 November 2015 Page 121 of 168
Figure 32 – SQL Server Objects
For the purpose of our demonstration, click Cancel in the above window.
In the Select a page pane, select Status. On this page you can grant or
deny the login permission to connect to the server. Ensure the Grant option
is selected.
Ensure that the Enabled option is selected.
Finally, click OK and the login is created.
Database Management Study Guide | V1.1 November 2015 Page 122 of 168
NOTE
A domain is an environment or location of all values that data elements may
contain.
If you are confused or not sure about your domain, do the following:
In most cases, the domain name will be the username that you use to login
to Microsoft SQL Server, e.g. PEROOT\nceba.
Database Management Study Guide | V1.1 November 2015 Page 123 of 168
Figure 33 – SQL Server Role member
You can add the role to one of the built-in server roles if you want, but for now
leave all boxes clear and click OK.
User-defined server roles can also be created using T-SQL. Execute the
following query:
USE [master]
GO
CREATE SERVER ROLE [BulkAdminAndDBCreator]
GO
ALTER SERVER ROLE [BulkAdminAndDBCreater] ADD MEMBER [DOMAIN\nceba]
GO
Database Management Study Guide | V1.1 November 2015 Page 124 of 168
USE master
GRANT ADMINISTER BULK OPERATIONS TO [BulkAdminAndDBCreater]
GO
USE master
GRANT CREATE ANY DATABASE TO [BulkAdminAndDBCreater]
By default, every user belongs to the public database role. The user will
inherit all permissions of this role until explicit permissions are granted.
A guest user is disabled by default. Since a guest is inherited by any login
that has access to the database, any permission granted to this account is
also inherited by those users.
Database Management Study Guide | V1.1 November 2015 Page 125 of 168
Figure 34 – User permissions
In the Select Objects dialog box, select Tables and click OK.
Click the Browse button and select the boxes next to the dbo.Cars and
dbo.Shapes tables and click OK.
In the Securables section, select the Employee table.
In the Explicit section, select the boxes in the Grant section for the
following permissions: Insert, Select, Update and Delete.
Repeat the above two steps for JobCandidate table.
NOTE
When creating a user role, you may have to use a different user name
because your default login name may have already been in existence as
another role.
In the Select a Page pane, select Extended Properties. You can include
metadata about the login here if you like; for now, leave it and click OK.
Database Management Study Guide | V1.1 November 2015 Page 126 of 168
We can also create a user using T-SQL. Also note that you can use the SQL
Server Authentication instead of Windows Authentication.
A contained user can be created from a Windows login or SQL Server with a
password. Using a database user on an existing login will not create a
contained database. Contained Database Authentication must be enabled at
the server and database level before any contained user is created. Let us now
create a contained database user:
Open SSMS and connect to the server. On the Object Explorer, right-click
the server name and select Properties from the menu.
Select Advanced from the Select a page pane. In the Containment section,
set the Enable Contained Databases option to True and click OK.
Now open a new query window.
Type and execute the following T-SQL statement:
USE master
GO
CREATE DATABASE MyContainedDB
USE master
GO
Exec sp_configure 'contained database authentication', 1;
GO
Reconfigure;
USE [master]
GO
ALTER DATABASE [MyContainedDB] SET CONTAINMENT = PARTIAL
GO
NOTE
SP_CONFIGURE is a tool to display and change SQL Server settings. When
changing the settings you should be careful because they affect your
instance and any dubious action can affect instance performance,
availability, and so on.
Database Management Study Guide | V1.1 November 2015 Page 127 of 168
Figure 35 – SQL Server Properties
Benefits Limitations
Data can now be easily Data is inaccessible while files
migrated. are being moved.
When AlwaysOn is configured,
in the event of failover a user
can connect to the server
without any security issues.
9.3 RAID
RAID (Redundant Array of Inexpensive Devices) is a standard for hard drive
fault tolerance. RAID uses a multiple hard drive configuration. The amount and
type of fault tolerance provided depends on which RAID level is implemented.
Microsoft Windows NT/2000 uses RAID levels 0, 1 and 5.
Database Management Study Guide | V1.1 November 2015 Page 128 of 168
NOTE
Fault-tolerant systems using RAID should never be used as a replacement for
regular backup of servers and local hard disks.
Database Management Study Guide | V1.1 November 2015 Page 129 of 168
9.4 Other types
9.4.1 Volume sets
Combining from 2 to 32 areas of unformatted free space (on one or more
physical drives) creates a volume set. These spaces form one large, logical
volume set that is treated like a single partition. Volume sets do not provide
fault tolerance and are simply a means of organising hard disk space.
NOTE
When it comes to deciding which files and folders to back up, a general rule
of thumb is: ‘if you cannot do without it, back it up’.
Database Management Study Guide | V1.1 November 2015 Page 130 of 168
Perform a network backup when the critical data is on multiple servers.
Perform multiple local backups when the critical data is on workstations.
For the advantages and disadvantages of network backups and local backups,
see Table 14 – Comparing network and local backups.
Advantages Disadvantages
One user can perform the Users must copy their
backup. important files to the
Network Requires fewer tape server.
backup drives. Increases network traffic.
Entire network is backed Requires greater
up. planning.
Each user is responsible
Fewer network resources
Local backup for backing up data on
committed.
individual workstations.
How critical the data is to the organisation – the more critical, the more
frequent.
How frequently the data changes.
NOTE
It is good practice to schedule backups when network usage is low.
Database Management Study Guide | V1.1 November 2015 Page 131 of 168
9.6.1 Full, differential, transactional log, file groups and
incremental backup types
Database Management Study Guide | V1.1 November 2015 Page 132 of 168
database itself and is
identified as part of a
chain that can be used
for restore.
Backs up all data that Full plus every daily
Incremental has changed since the Yes incremental since the
last backup of any kind. last full backup
A common tape rotation method called the child, parent and grandparent
method makes management of the tapes a lot easier. This method is explained
in Table 16 – Child, parent, grandparent rotation method.
Database Management Study Guide | V1.1 November 2015 Page 133 of 168
Figure 37 – Object Explorer
Right-click on the database that you need to back up and select Tasks >
Backup. You will be presented with the screen shown in Figure 38.
Figure 38 – Backup
Ensure that the backup is set properly and click OK. It should back up to the
specified folder. A dialog box will tell you whether or not it was successful.
When successful, use Windows Explorer to navigate to the folder that contains
Database Management Study Guide | V1.1 November 2015 Page 134 of 168
the database backup that you have created. Once there, right-click on your
backup file and select Send To > Compressed (zipped) folder (see Figure
39).
It is recommended that you keep the same name as that of the backup. You
have now successfully created a backup of your database and zipped it.
Required reading
Database Management Study Guide | V1.1 November 2015 Page 135 of 168
Chapter 9, 11, 15 19 & 38 - Microsoft SQL Server 2014 UNLEASHED.
Database Management Study Guide | V1.1 November 2015 Page 136 of 168
Unit 10 – Project
This project will test your understanding of all the sections covered in the
previous units. You can choose any one of the projects given (consult your
lecturer in this regard). A mark sheet for each project will also be provided.
You need to supply user documentation on how to set up and run your
program. All your project content must be submitted digitally on a CD, DVD or
flash drive.
No matter which project you do, you must create the following script files. To
create a script file (in Microsoft SQL Server Management Studio), select Save
from the File menu when you have finished typing all the necessary code and
save it to disk. Script files should have a .SQL file extension.
Create a script file that includes the code for creating the database and all
of the tables required in the project. PRIMARY KEY, FOREIGN KEY, UNIQUE
and CHECK constraints must be included. Make use of the IDENTITY
property, DEFAULT values and constraints. Remember that master/parent
tables must be created first.
Create a script file to insert data into your user-created tables. Add at least
four records for each table without foreign keys and seven records for
each table that does contain a foreign key.
Create a script file to create at least two triggers for your project. There
are no specifications for what types of triggers you must create. You should
apply your knowledge and create triggers that you think would be
appropriate.
Database Management Study Guide | V1.1 November 2015 Page 137 of 168
Using the GUI, create a full backup of your database and send it to a zipped
folder.
Each script file must have a header section (using comments) that contains
the following information:
o Script file name
o Programmer name
o Date
o A short description of what the script file does
Save all of the script files together with the backup onto a disk and hand it
in along with printouts of the script files. Provide clear instructions in your
user documentation on how to execute the views and stored procedures
(including the arguments that need to be passed to the stored procedures).
In your user documentation you should also include author and date details,
together with the purpose and description of the project.
Database Management Study Guide | V1.1 November 2015 Page 138 of 168
Project 1 – MMORPG
A new company has developed a breakthrough Massive Multiplayer Online Role
Playing Game (MMORPG). An MMORPG is a computer game that is played over
the Internet, connecting to a server where other players from around the world
are also playing the same game. You are able to ‘see’ and communicate with
these other players when online.
This company has recruited you to be their database designer. The database
that you must design will manage the accounts of all players registered for this
online game. First, each account must have a unique name. This will be the
name that players use to log on to the game server. Players need to pay a fee
every month for having an account and when their time runs out, the account
must be blocked and only unblocked when they have purchased more time.
Each account has a number of unique characters that have been created by
the user. All characters have names and have a skill level. There must be a
table in the database that logs any errors that occur. Make sure that certain
errors have a certain type so that they are easier to find.
When playing the game with one of your account’s characters, you may find
and pick up items. These items are then stored in your character’s inventory.
No item is unique, unfortunately, so other characters may have the same item
as you. An item has a name and a description. The inventory has eight open
slots for different types of items to go into. Items that are the same can stack
in the same slot; therefore, you must keep a record of the quantity.
Specifications
Create the following views:
Database Management Study Guide | V1.1 November 2015 Page 139 of 168
spAddItem – Adds an item to a character’s inventory. Make sure there is
space before adding the item.
spAddChar – Adds a specified character to a specified account.
spSendLetter – Prints out a letter for each account, indicating how much
time they have left. An optional argument that can be used to send latest
news must also be included.
Database Management Study Guide | V1.1 November 2015 Page 140 of 168
Project Evaluation – Project 1 (DBMM-16)
Total: 120
Database Management Study Guide | V1.1 November 2015 Page 141 of 168
Project 2 – Tygervalley Pet Shelter
Tygervalley Pet Shelter (TPS) receives food donations from a group of pet food
manufacturers. TPS relies on each manufacturing company for a particular
need. For example, Veggie Land supplies all vegetables and Premier Seed
Suppliers supply all seeds.
The different food types are allocated to the animals according to their
category. For example, food type ‘seeds’ is allocated to category ’Birds’, while
food type ‘vegetables’ is allocated to categories ‘Mammals’ and ‘Birds’.
Each animal category is subdivided into different pet types. For example, the
mammal record could relate to pet types ‘Dog’ and ‘Cat’.
TPS has recruited you to be their database designer. The database that you
must design will store information on their suppliers, food types, animal
categories and pet types.
Specifications
Create the following views:
Database Management Study Guide | V1.1 November 2015 Page 142 of 168
sp_NewPetType – Insert a new pet type record. Remember to check
whether or not the primary key argument is an existing category primary
key.
p_UpdateStock – Update an existing pet type record. The procedure must
make use of three arguments – 1: pet type primary key, 2: the number of
animals to be added/subtracted, 3: bit number representing addition (1) or
subtraction (0).
sp_DeleteFoodType – Delete a specified food type and all dependent/child
records. However, only delete the type if it is contained in the
vw_ExpiredFoodDetails view.
sp_Report – Print a specified manufacturing company’s details and all its
expired products in use. The report should also display a header as well as
the current date and time. Retrieve the products by using the
vw_ExpiredFoodDetails view. The report should be displayed as follows:
Generated:
Jan 18 2013 8:05AM
Company ID: 2
Company Name: Veggie Land
Contact Number: (051) 861 2571
Email: [email protected]
__________________________________________________
Food ID Food Type
__________________________________________________
1 Green Vegetable Mix
6 Carrots
____________________
Total Records: 2
____________________
Database Management Study Guide | V1.1 November 2015 Page 143 of 168
Project Evaluation – Project 2 (DBMM-16)
Total: 120
Database Management Study Guide | V1.1 November 2015 Page 144 of 168
Project 3 – Online Flight Booking
A South African Flight Booking Agency wants to develop its online booking
system to afford its clients a self-service facility. The system will allow
customers to check and reserve flights as and when required. Customers will
be able to view flights according to dates, prices, and departure and arrival
points. Any customer will be able to view flights on the system but only
registered customers/members can make a reservation.
A ticket can only be reserved for available flights. Each client/customer can
only reserve one ticket per journey and there can be more than one passenger
per ticket. The system keeps track of flights by customers’ names, dates and
destinations. The system will allocate a status of registered and not registered
to a customer when an ID number is entered. A booking is made using the
customer’s name, flight number and date, while an optional discount is
available for seniors and minors. Based on their ID number, any customer over
65 years is considered a senior citizen and anyone under 16 years of age is a
minor. Minors may not have ID numbers, which would make it impossible to
secure a discount when booking online. Customers are given a choice of
payment options.
Specifications
Create the following views:
• vw_Flight – All flights appearing on the website, their availability and prices
per reservation.
• vw_AffordableFlight – Select the top three flights with unchanged reservation
and booking price.
• vw_SeniorUsers - Select all senior users who qualify for a discount based on
their age.
• vw_OnboardCustomers – Select all registered member names as well as the
total number of classes that each member will qualify for. HINT: Use the
COUNT function.
Database Management Study Guide | V1.1 November 2015 Page 145 of 168
sp_AddNewFlights – Insert new flights as they become available.
sp_UpdateFlyingTimes – Update the flying times as requested by customers
based on demand.
sp_DeleteTicket – Delete a ticket record. A ticket may only be deleted when
it has been used or if the date has expired.
sp_Report – Print the details of a specified flight class and each registered
member’s name and contact number assigned to the class. Your report's
output should have exactly the same format as that shown below:
Book ID: 3
customer name: Janne [Date: Oct 22 2015]
flight number: 4 Journey: One way
Use a counter to print the ’No.’ column values, and ensure that the column
values are properly aligned.
Database Management Study Guide | V1.1 November 2015 Page 146 of 168
Project Evaluation – Project 3 (DBMM-16)
Total: 120
Database Management Study Guide | V1.1 November 2015 Page 147 of 168
Unit 11 – Test your knowledge
3. What data type should be used to store a feedback field in a table for
which the user is allowed to enter comments of varying length?
5. What is the difference between the UNIQUE constraint and the PRIMARY
KEY constraint?
a. WHERE
b. FROM
c. ORDER BY
d. INTO
Database Management Study Guide | V1.1 November 2015 Page 148 of 168
14. Name three advantages of using indexes.
19. What is the difference between the -- and /*…*/ comment symbols?
24. SQL Server 2014 runs inside a type of framework. What is this
framework?
a. JDK
b. CLR
c. .NET
d. Java runtime environment
25. What file extension is used for the primary data file?
26. What file extension is used for the secondary data file?
27. What file extension is used for the transaction log file?
29. What is the client tool used to communicate with the server called?
31. Which data type is used for checking when the row was last updated?
a) REFERENCES
b) FOREIGN_KEY
c) UNIQUE
d) INDEXER
Database Management Study Guide | V1.1 November 2015 Page 149 of 168
33. What does the keyword DROP do?
a) ORDER BY
b) SELECT
c) WHERE
d) ON
45. What is the difference between network backups and local backups? Give
advantages and disadvantages.
48. Microsoft SQL Server offers three security choices which are:
a) INTEGRATED SECURITY
STANDARD SECURITY
MIXED SECURITY
Database Management Study Guide | V1.1 November 2015 Page 150 of 168
b) MULTIPLE SECURITY
SIMPLE SECURITY
COMPLEX SECURITY
c) ORDERED SECURITY
MIXED SECURITY
SEQUENTIAL SECURITY
50. Can a table in a database have as many clustered indexes as the user
wants?
53. An index can be created using either _______or SQL Server Studio.
54. Indexes are organised as________, and each page in the index is called
an index node.
55. How would you differentiate between a view and a stored procedure?
Database Management Study Guide | V1.1 November 2015 Page 151 of 168
Glossary
Term Description
Fields corresponding to the attributes of the objects
Columns
described by the table.
The SQL command which marks the finalisation of a
COMMIT
database transaction.
Short for Current Set Of Records in some database
Cursor languages; a database object pointing to a current
selected set of records.
Data Information collected and formatted in a specific way.
Collection of information organised into related tables of
Database
data and definitions of data objects.
A key that identifies records in a table by matching a
Foreign key primary key in a different table. The foreign keys are
used to cross-reference tables.
A database feature (a list of keys or keywords), allowing
Index
searching and locating data quickly within a table.
INSERT The SQL command used to add a new record to a table.
The SQL command used to retrieve data from 2 or more
JOIN database tables within an existing relationship based
upon a common attribute.
The primary system database. Without it, SQL Server
Master database
cannot start.
Short for Open Database Connectivity, a standard
database access technology developed by Microsoft. The
OBDC
purpose of OBDC is to allow the accessing of any DBMS
from any application.
The SQL command which is the primary means of
SELECT
retrieving data from an RDBMS.
A set of SQL statements stored within a database server
and executed as a single entity. Using stored procedures
has several advantages over using inline SQL
Stored procedure
statements, like improved performance and separation
of the application logic layer from the database layer in
n-tier applications.
Data in an RDBMS, arranged in rows and columns, which
Table
defines a database entity.
A group of SQL database commands regarded and
Transaction
executed as a single entity.
Database Management Study Guide | V1.1 November 2015 Page 152 of 168
A special type of stored procedure executed
Trigger
automatically when certain events take place.
Bibliography
Textbooks
Rankins R., Bertucci P., Gallelli C. & Silverstein A.T. 2014. Microsoft SQL
Server 2014 - UNLEASHED. ISBN 978-0-67233729-1.
Suggested reading
LeBlanc, P. 2013. Microsoft SQL Server 2012 Step by Step. Sebastopol,
California: O’Reilly Media, Inc. ISBN 978-0-7356-6386-2.
Websites
W3schools: www.w3schools.com/sql/
About.com: databases.about.com/od/sqlserver/
WiseOwl: https://www.youtube.com/watch?v=2-1XQHAgDsM
SQLCoffee: http://www.sqlcoffee.com/SQLServer2014_0006.htm
Database Management Study Guide | V1.1 November 2015 Page 153 of 168
Unit Exercise Checklist
(DBMM-16 V1.0)
Please note that unless all of your exercises have been signed off by the
lecturer you will not be allowed to book for the exam.
1 1 6
2 2 7
3 3 8
4 4
5
Section 7.7 Section 8.3 Section 9.8
1 1 1
2 2 2
3 3 3
4
Database Management Study Guide | V1.1 November 2015 Page 154 of 168
Database Management Study Guide | V1.1 November 2015 Page 154 of 168
Database Management Evaluation Form
(DBMM-16 V1.0)
How would you evaluate the Database Management study guide? Place a or in one of the
five squares that best indicates your choice. Your response will help us to improve the quality
of the study guides and courses, and will be much appreciated.
Very
Poor Fair Good Excellent
poor
Please note any errors that you found in the study guide.
Please remove this evaluation form and return it to your lecturer or senior lecturer so that it can
be forwarded to the Division for Courseware Development.
Thank you.
Database Management Study Guide | V1.1 November 2015 Page 155 of 168
Contact details
Pretoria Campus
Potchefstroom Campus
Menlyn Corporate Park, Building A
16 Esselen Street, Cnr Esselen Street
175 Corobay Avenue Cnr Garsfontein, Pretoria
& Steve Biko Avenue, Die Bult, Potchefstroom
PostNet Suite A147, Private Bag X18,
P.O. Box 19900, Noordbrug, 2522
Lynnwood Ridge, 0040
Tel: +27 (0)18 297 7760, Fax: +27 (0)18 297 7783
Tel: +27 (0)12 348 3060, Fax: +27 (0)12 348 3063
Email: [email protected]
Email: [email protected]