DatabaeLab 2 6
DatabaeLab 2 6
Once the statement executes successfully, you can view the newly created database in
the Object Explorer. If the new database does not appear, you can click
the Refresh button or press F5 keyboard to update the object list.
Second, enter the name of the database e.g., SampleDb and click
the OK button.
Third, view the newly created database from the Object Explorer:
In this tutorial, you have learned how to create a new database using SQL
Server CREATE DATABASE statement and SQL Server Management Studio.
The DROP DATABASE statement allows you to delete one or more databases
The IF EXISTS option is available from SQL Server 2016 (13.x). It allows you to
conditionally delete a database only if the database already exists. If you attempt to
delete a nonexisting database without specifying the IF EXISTS option, SQL Server will
issue an error.
First, the DROP DATABASE statement deletes the database and also the
physical disk files used by the database. Therefore, you should have a backup of
the database in case you want to restore it in the future.
Second, you cannot drop the database that is currently being used.
Second, uncheck the Delete backup and restore history information for
databases check box, check the Close existing connections check box, and click
the OK button to delete the database.
Third, verify that the database has been dropped from the Object Explorer.
Task
1. The following illustrates the BikeStores database diagram:
2. Create database BikeStores
3. Create Tables as given below in diagram.
Lab 3 Tasks
Data Definition Language (DDL)
In this lab, you will learn how to create and alter a new tables and how to
apply constraints on the table in SQL Server using commands or SQL Server
Management Studio.
SQL Constraints
Constraints are used to limit the type of data that can go into a table.
Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the
table is created (with the ALTER TABLE statement).
PRIMARY KEY
NOT NULL
UNIQUE
FOREIGN KEY
CHECK
DEFAULT
IDENTITY
1. PRIMARY KEY
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain unique values. It is normal to just use running numbers, like 1, 2, 3, 4, 5, … as
values in Primary Key column.
It is a good idea to let the system handle this for you by specifying that the Primary Key should be set to
identity (1, 1). IDENTITY (1, 1) means the first value will be 1 and then it will increment by 1. Each table
should have a primary key, and each table can have only ONE primary key.
SCHOOL
If you use the Designer tools in SQL Server, you can easily set the primary Key in a table just by right-click
and select “Set primary Key”.
2. FOREIGN KEY
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
CLASS:
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
The FOREIGN KEY constraint also prevents that invalid data from being inserted into the foreign key
column, because it has to be one of the values contained in the table it points to.
If you want to use the designer, right-click on the column that you want to be the Foreign Key and
select “Relationships…”
Click on the “Add” button and then click on the small “…” button. Then the following window pops up
(Tables and Columns):
Here you specify the primary Key Column in the Primary Key table and the Foreign Key Column in the
Foreign Key table.
4. UNIQUE
The UNIQUE constraint uniquely identifies each record in a database table. The UNIQUE and PRIMARY
KEY constraints both provide a guarantee for uniqueness for a column or set of columns.
Note! You can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per
table.
If you want to use the designer, right-click on the column that you want to be UNIQUE and select
“Indexes/Keys…”
Then click “Add” and then set the “Is Unique” property to “Yes”:
5. CHECK
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a single column it allows only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on values in
other columns in the row.
In this case, when we try to insert a Customer Number less than zero we will get an error message.
If you want to use the designer, right-click on the column where you want to set the constraints and
select “Check Constraints…”
Then click “Add” and then click “…” in order to open the Expression window:
In the Expression window you can type in the expression you want to use:
6. DEFAULT
The DEFAULT constraint is used to insert a default value into a column. The default value will be added
to all new records, if no other value is specified.
We can use the designer tools to specify that a Primary Key should be an identity column that is
automatically generated by the system when we insert data in to the table.
Click on the column in the designer and go into the Column Properties window
ALTER TABLE
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
3. To change the data type of a column in a table, use the following syntax:
If we use CREATE TABLE and the table already exists in the table we will get an error message,
So if we combine CREATE TABLE and ALTER TABLE we can create robust database scripts that gives no
errors, as the example shown below:
INSERT INTO
The INSERT INTO statement is used to insert a new row in a table.
The first form doesn't specify the column names where the data will be inserted, only their values:
Note! You need at least to include all columns that cannot be NULL.
When you have created the tables, you can easily insert data into them using the designer tools. Right-
click on the specific table and select “Edit Top 200 Rows”:
UPDATE
The UPDATE statement is used to update existing records in a table.
Note! Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be
updated!
DELETE
The DELETE statement is used to delete rows in a table.
Note! Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which
record or records that should be deleted. If you omit the WHERE clause, all records will be
deleted!
This means that the table structure, attributes, and indexes will be intact (not damaged or impaired in any way)
Note! Make sure to do this only when you really mean it! You cannot UNDO this statement!
You delete data in the designer by right-click on the row and select “Delete”
SELECT
The SELECT statement is probably the most used SQL command. The SELECT statement is used for
retrieving rows from the database and enables the selection of one or many rows or columns from one
or many tables in the database.
To be continued…….
Lab 4 Tasks
In this lab, you will learn Select statement with different operators on the table
in SQL Server using commands or SQL Server Management Studio.
SELECT
The SELECT statement is probably the most used SQL command. The SELECT statement is used for
retrieving rows from the database and enables the selection of one or many rows or columns from one
or many tables in the database.
The full syntax of the SELECT statement is complex, but the main clauses can be summarized.
Example:
This simple example gets all the data in the table CUSTOMER. The symbol “*” is used when you want
to get all the columns in the table.
If you only want a few columns, you may specify the names of the columns you want to retrieve,
example:
If you use the “order by” keyword, the default order is ascending (“asc”). If you want the order to be
opposite, i.e., descending, then you need to use the “desc” keyword.
SELECT DISTINCT
In a table, some of the columns may contain duplicate values. This is not a problem, however,
sometimes you will want to list only the different (distinct) values in a table.
The DISTINCT keyword can be used to return only distinct (different) values.
Note! SQL uses single quotes around text values, as shown in the example above.
Operators
With the WHERE clause, the following operators can be used:
Examples:
LIKE Operator
The LIKE operator is used to search for a specified pattern in a column.
Note! The "%" sign can be used to define wildcards (missing letters in the pattern) both before and
after the pattern.
BETWEEN Operator
The BETWEEN operator selects a range of data between two values. The values can be numbers, text, or
dates.
Wildcards
SQL wildcards can substitute for one or more characters when searching for data in a database.
Note! SQL wildcards must be used with the SQL LIKE operator.
The OR operator displays a record if either the first condition or the second condition is true.
The TOP clause can be very useful on large tables with thousands of records. Returning a large number
of records can impact on performance.
Alias
You can give a table or a column another name by using an alias. This can be a good thing to do if you
have very long or complex table names or column names.
Joins
SQL joins are used to query data from two or more tables, based on a relationship between certain
columns in these tables.
To be continued…….
Lab 5 Tasks
In this Lab, you will learn about various kinds of SQL Server joins that allow you to
combine data from two tables.
Joins
SQL joins are used to query data from two or more tables, based on a relationship between
certain columns in these tables.
Select all records from Select all records from Select all records from Select all records from
Table A and Table B, Table A, along with Table B, along with Table A and Table B,
where the join condition records from Table B for records from Table A for regardless of whether the
is met. which the join condition is which the join condition is join condition is met or
met (if at all). met (if at all). not.
Inner Join
Left Join
Note that since there were no matching records for Alina Majid in our orders table,
the order_amount is NULL, which simply means there is no data for these fields.
Right Join
Right join is a mirror version of the left join and allows to get a list of all orders, appended with customer
information.
Note that since there were no matching customer records for orders amount in 100.2 and 102,
the CustomerId ,FirstName and LastName fields are NULL in the resulting set.
Full Join
Finally, for a list of all records from both tables, we can use a full join.
Task
Write SQL queries to find:
1. FistName and LastName of Customers who have booked at least one table
3. Number of times a table has been booked along with it's Details
Profession
6. All the information about Customers along with their BOOKING details
Lab 6 Tasks
In this Lab, you will learn SQL Server Scripting
SQL Scripts
A SQL script is a collection of SQL statements that you can execute in one operation. You can use
any kind of SQL commands, such as insert, select, delete, update, etc. In addition you can define
and use variables, and you may also use program flow like If-Else, etc. You may also add
comments to make the script easier to read and understand.
Using Comments
Using comments in you SQL script is important to make the script easier to read and understand.
In SQL we can use 2 different kinds of comments:
Single-line comment
Multiple-line comment
Single-line comment
We can comment one line at the time using “--” before the text you want to comment out.
Syntax:
Multiple-line comment
We can comment several line using “/*” in the start of the comment and “*/” in the end
of the comment.
Variables
MS SQL has two types of variables:
1. Local variable
2. Global variable.
Local variable:
A user declares the local variable.
By default, a local variable starts with @.
Every local variable scope has the restriction to the current batch or
procedure within any given session.
Global variable:
The system maintains the global variable. A user cannot declare them.
The global variable starts with @@
It stores session related information.
The ability to using variables in SQL is a powerful feature. You need to use the keyword
DECLARE when you want to define the variables. Local variables must have the symbol
“@” as a prefix. You also need to specify a data type for your variable (int, varchar(x), etc.).
declare @local_variable data_type
If you have more than one variable you want to declare:
declare
@myvariable1 data_type,
@myvariable2 data_type,
........
When you want to assign values to the variable, you must use either a SET or a SELECT
statement.
Asim Ali Fayyaz (Research Associate)
[email protected]
DATABASE LAB MANUAL
If you want to see the value for a variable, you can e.g., use the PRINT command like this:
You can assign a value to the variable from a select statement like this:
You can also use a variable in the WHERE clause LIKE, e.g., this.
Global Variables
Global variable names begin with a @@ prefix. You do not need to declare them, since the server
constantly maintains them. They are system-defined functions and you cannot declare them.
1. @@CONNECTIONS
2. @@MAX_CONNECTIONS
3. @@CPU_BUSY
4. @@ERROR
5. @@IDENTITY
6. @@IDLE
7. @@IO_BUSY
8. @@LANGID
9. @@LANGUAGE
10. @@MAXCHARLEN
11. @@PACK_RECEIVED
12. @@PACK_SENT
13. @@PACKET_ERRORS
14. @@ROWCOUNT
15. @@SERVERNAME
16. @@SPID
17. @@TEXTSIZE
18. @@TIMETICKS
19. @@TOTAL_ERRORS
20. @@TOTAL_READ / @@TOTAL_WRITE
21. @@TRANCOUNT
22. @@VERSION
Global variable names begin with a @@ prefix. You do not need to declare them, since the server constantly
maintains them. They are system-defined functions and you cannot declare them.
@@CONNECTIONS
The number of logins or attempted logins since SQL Server was last started.
@@MAX_CONNECTIONS
The maximum number of simultaneous connections that can be made with SQL Server in this
computer environment. The user can configure SQL Server for any number of connections less than
or equal to the value of @@max_connections with sp_configure ''number of user
connections''.
@@CPU_BUSY
The amount of time, in ticks, that the CPU has spent doing SQL Server work since the last time SQL
Server was started.
@@ERROR
Commonly used to check the error status (succeeded or failed) of the most recently executed
statement. It contains 0 if the previous transaction succeeded; otherwise, it contains the last error
number generated by the system. A statement such as:
IF @@ERROR <> 0
PRINT 'Your error message';
IF @@ERROR != 0 return causes an exit if an error occurs.
Every Transact-SQL statement resets @@error, including print statements or if tests, so the
status check must immediately follow the statement whose success is in question.
@@IDENTITY
The last value inserted into an IDENTITY column by an insert or select into
statement. @@identity is reset each time a row is inserted into a table. If a statement inserts
multiple rows, @@identity reflects the IDENTITY value for the last row inserted. If the affected
table does not contain an IDENTITY column, @@identity is set to 0.
The value of @@identity is not affected by the failure of an insert or select into statement,
or the rollback of the transaction that contained it. @@identity retains the last value inserted into
an IDENTITY column, even if the statement that inserted it fails to commit.
Example
@@IDLE
The amount of time, in ticks, that SQL Server has been idle since it was last started.
Example
SELECT @@IDLE * CAST(@@TIMETICKS AS float) AS 'Idle microseconds',
GETDATE() AS 'as of'
Output
Hide Copy Code
Idle microseconds as of
---------------------- -----------------------
11340000000 2009-08-19 22:07:19.903
@@IO_BUSY
The amount of time, in ticks, that SQL Server has spent doing input and output operations since it
was last started.
Example
SELECT @@IO_BUSY*@@TIMETICKS AS 'IO microseconds',
GETDATE() AS 'as of'
Output
IO microseconds as of
--------------- -----------------------
5906250 2009-08-19 22:09:44.013
@@LANGID
Example
SET LANGUAGE 'Italian'
SELECT @@LANGID AS 'Language ID'
SET LANGUAGE 'us_english'
SELECT @@LANGID AS 'Language ID'
Output
@@LANGUAGE
Example
SELECT @@LANGUAGE AS 'Language Name';
@@MAXCHARLEN
The maximum length, in bytes, of a character in SQL Server's default character set.
Example
SELECT @@MAX_PRECISION AS 'Max Precision'
Output
-------------
38
@@PACK_RECEIVED
The number of input packets read by SQL Server since it was last started.
Example
SELECT @@PACK_RECEIVED AS 'Packets Received'
Output
Packets Received
----------------
8998
@@PACK_SENT
The number of output packets written by SQL Server since it was last started.
Example
SELECT @@PACK_SENT AS 'Pack Sent'
Output
Pack Sent
-----------
9413
@@PACKET_ERRORS
The number of errors that have occurred while SQL Server was sending and receiving packets.
Example
SELECT @@PACKET_ERRORS AS 'Packet Errors'
Output
Packet Errors
-------------
0
@@ROWCOUNT
The number of rows affected by the last command. @@rowcount is set to 0 by any command
which does not return rows, such as an if statement. With cursors, @@rowcount represents the
cumulative number of rows returned from the cursor result set to the client, up to the last fetch
request.
Example
IF @@ROWCOUNT = 0
PRINT 'Warning: No rows were updated';
Output
'Warning: No rows were updated'
@@SERVERNAME
The name of the local SQL Server. You must define a server name with sp_addserver, and then
restart SQL Server.
Example
SELECT @@SERVERNAME AS 'Server Name'
Output
MY_SERVER_WINDOWS_2003
@@SPID
Example
SELECT @@SPID AS 'ID', SYSTEM_USER AS 'Login Name', USER AS 'User Name'
Output
ID Login Name User Name
------ ----------------------------------------------------
55 MY_SERVER_WINDOWS_2003\Administrator dbo
@@TEXTSIZE
The current value of the set textsize option, which specifies the maximum length, in bytes, of text or
image data to be returned with a select statement. Defaults to 32K.
Example
SET TEXTSIZE 2048
SELECT @@TEXTSIZE AS 'Text Size'
Output
Text Size
-----------
2048
@@TIMETICKS
The number of microseconds per tick. The amount of time per tick is machine dependent.
Example
SELECT @@TIMETICKS AS 'Time Ticks';
Output
Time Ticks
-----------
31250
@@TOTAL_ERRORS
The number of errors that have occurred while SQL Server was reading or writing.
Example
SELECT @@TOTAL_ERRORS AS 'Errors', GETDATE() AS 'As of'
Output
Errors As of
----------- -----------------------
0 2009-08-19 22:47:51.937
@@TOTAL_READ / @@TOTAL_WRITE
The number of disk reads by SQL Server since it was last started.
Example
SELECT @@TOTAL_READ AS 'Reads', @@TOTAL_WRITE AS 'Writes', GETDATE() AS 'As of'
Output
Reads Writes As of
----------- ----------- -----------------------
861 91 2009-08-19 23:36:26.763
@@TRANCOUNT
The nesting level of transactions. Each begin transaction in a batch increments the transaction count.
When you query @@trancount in chained transaction mode, its value is never zero since the query
automatically initiates a transaction.
@@VERSION
Example
SELECT @@VERSION AS 'SQL Server Version'
Flow Control
As with other programming languages you can use different kind of flow control, such as IFELSE,
WHILE, etc, which is very useful.
IF – ELSE
BEGIN…END
If more than one line of code is to be executed within an IF sentence you need to use
WHILE
We can also use WHILE, which is known from other programming languages.
Example:
We are using the CUSTOMER table:
As you can see the code inside the WHILE loop is executed as long as “AreaCode” for
CustomerId=1 is less than 54. For each iteration is the “AreaCode” for that customer
incremented with 1.
CURSOR
In advances scripts, CURSORs may be very useful. A CURSOR works like an advanced WHILE
loop which we use to iterate through the records in one or more tables.
CURSORS are used mainly in stored procedures, triggers, and SQL scripts.
Example:
We use the CUSTOMER table as an example:
We will create a CURSOR that iterate through all the records in the CUSTOMER table and check
if the Phone number consists of 11 digits, if not the script will replace the invalid Phone number
with the text “Phone number is not valid”.
Declare SQL variables to contain the data returned by the cursor. Declare one variable
for each result set column.
Associate a SQL cursor with a SELECT statement using the DECLARE CURSOR statement.
The DECLARE CURSOR statement also defines the characteristics of the cursor, such as
the cursor name and whether the cursor is read-only or forward-only.
Use the OPEN statement to execute the SELECT statement and populate the cursor.
Use the FETCH INTO statement to fetch individual rows and have the data for each
column moved into a specified variable. Other SQL statements can then reference those
variables to access the fetched data values.
When you are finished with the cursor, use the CLOSE statement. Closing a cursor frees
some resources, such as the cursor's result set and its locks on the current row.
The DEALLOCATE statement completely frees all resources allocated to the cursor,
including the cursor name.