CSC351_Lab_Manual_Database Systems
CSC351_Lab_Manual_Database Systems
CSC351_Lab_Manual_Database Systems
Laboratory Manual
record is as important as the experiment itself. Please follow these guidelines for efficient performance in th
laboratory:
Attend the lab orientation to familiarize yourself with the lab setup.
Write clear and well-documented code, avoiding plagiarism and unauthorized collaboration.
Seek help from lab instructors or peers if you encounter difficulties with programming concepts.
Regularly back up your code and project files to prevent data loss.
If collaboration is allowed, work effectively with peers, ensuring each member contributes meaningfully.
Maintain a clean and organized workspace for better focus and efficiency.
Thoroughly test your code to identify and fix errors before submission.
1. Engage in lab discussions, share insights, and actively participate to enhance the learning experience.
Safety Precautions
1. Handle equipment carefully to prevent damage and avoid placing liquids near electronic devices.
3. Save work frequently and use surge protectors to prevent data loss due to power issues.
4. Keep software and antivirus programs up to date and avoid downloading from untrusted sources.
6. Establish clear communication and collaboration guidelines when working with others.
Name:
Registration No.:
Student Signature:
Date:
Lab Instructor:
Grading Policy
Lab Performance 15%
Lab Report 15%
Lab Project +Viva 20%+10%
Final Lab Exam 40%
Rubrics
Lab Performance (Continuous Assessment) / Performance Test
2 Efficiency The code is fairly The code The code is huge and
efficient without is brute appears to be patched
force and
sacrificing unnecess together.
readability and arily long.
understanding.
Viva Voce
Project Viva
Responds well, Generally Non-responsive.
Responsiveness to quick and very Responsive and
1
Questions/ accurate all the accurate most of
Accuracy time. the times.
Demonstration of At ease with No grasp of
full knowledge of content and able information. Clearly no
Level of
the subject with to elaborate and knowledge of subject
2 understanding of
explanations and explain to some matter. No questions
the learned skill
elaboration. degree. are answered. No
interpretation made.
Project Presentation
Presentation is
Presentation is
clear Listener can follow
generally clear.
and logical. presentation with
A
1 Organization Listener can effort.
few minor points
easily Organization not
may be
follow line of well thought out.
confusing
reasoning
Is very confident
and explains the
details properly. Is confident to Has low confidence to
Proper eye some extent explain and deliver
contact is with quite less topic properly. Less
2 Confident
maintained all eye contact and eye contact and
the time with presentational presentational
proper gestures. gestures used.
presentational
gestures.
Responds well to
Reluctantly interacts
questions. Generally
Responsiveness to with audience.
3 Restates responsive to
Audience Responds poorly to
and summarizes questions.
questions.
when needed.
Team Work
Relays very little
Share Relays some basic
1 Relays a great deal information--some
Information information--most
of relates to the topic
information--all relates
relates to to the topic.
the topic.
Performs all duties
Performs nearly
Fulfill Team of Performs very little
2 all
duties assigned team duties.
duties
role
Lab’s Course Learning Outcomes
3 Select, From, Where all related Queries in SQL, Distinct and Order by clause 1
9 Subqueries 2
Activity:
SQL Server 2016 (13.x) RC1 and later require .NET Framework 4.6 for the Database
Engine, Master Data Services, or Replication. SQL Server setup automatically installs
.NET Framework. You can also manually install .NET Framework from Microsoft .NET
Framework 4.6 (Web Installer) for Windows.
1.4. Memory
1.5. Processor
2. Installation guide
Important Note:
2.1. connect your system with internet and download the developer edition
using this given link: https://www.microsoft.com/en-us/sql-server/sql-server-
downloads
2.2. Login on window with as Administrator
1:
2.3. Once downloaded then click on the .exe file and run.
2.4. Then click on Basic version to install.
2.6. Click on Install and eat pop corns until installation is done.
2.7. After installation is done click on install SSMS
Figure5:
2.8. Click on highlighted link. It will download .exe file of SSMS. After
downloading run .exe file.
Figure6: Version of SSMSfor installation
2.9. Click on Install and wait until installation is done successfully.
• Step 1
Right click on your database and select Task -> generate script.
Figure 8: Database_Scripts_With_Data_Select_Option
Database system Lab
Department of Computer Science
Step 2
Figure 9: Database_Scripts_With_Data_Introduction
• Step 3
Select the database object which you are all you need and then click next.
Step 4
Now you will be shown a window which asks you about how your script should be published.
Step 5
Select ‘Schema and data’ from type of data to script option and then click OK.
Step 6
Page 1 of 2
Database system Lab
Department of Computer Science
Click finish, now check the script file, it must be having the insert queries too.
Lab Tasks
CONCLUSION:
Page 2 of 2
Database system Lab
Department of Computer Science
___________________________________________________________________________
___________________________________________________________________________
__________________________________________________________________________
RUBRICS:
Instructor Signature
Page 3 of 2
Database system Lab
Department of Computer Science
PRACTICAL NO.02
DML, DDL, DCL commands
PLO CLO LL
5 1 P2
Objectives:
This lab provides an
To create database and table using SQL, Briefing various commands and their use
SQL Data
types
Page 4 of 2
Database system Lab
Department of Computer Science
Constraints in SQL
What is Constraints?
To maintain the data integrity, we use the constraints. Constraints are the rules which we applied on the
table’s column to ensure the data integrity.
We can add constraints on column while creating the table and can also add after creating the table.
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
INDEX - Used to create and retrieve data from the database very quickly
Page 5 of 2
Database system Lab
Department of Computer Science
Create Database:
Syntax:
Create Table:
Once a database is made it is easy to add tables in it, a table in SQL is like
Syntax:
Column_4 data_type
...,
);
INSERT:
Using this command we can Insert the records into the existing table
1. Explicit method
2. Implicit method
Explicit method
In this method user has to enter all the values into all the columns without anything omitting (or) left any
column data
Syntax:
Page 6 of 2
Database system Lab
Department of Computer Science
(OR)
Implicit Method:
In this method we can enter the values into the required columns in the table, so that user can omit (or) left
some columns data while he enters the records into the table
If the user omit any column data in the table then it automatically takes NULL
Syntax: INSERT INTO <TABLE NAME> (COL1, COL2….COLN) VALUES (VAL1, VAL2… VALN);
Lab Tasks:
1. Create a new database named Lab2
2. Create table with following schema Student (Registration Number: String, Name: String,
Page 7 of 2
Database system Lab
Department of Computer Science
CONCLUSION:
___________________________________________________________________________
___________________________________________________________________________
__________________________________________________________________________
RUBRICS:
Instructor Signature
Page 8 of 2
Database system Lab
Department of Computer Science
PRACTICAL NO.03
Basic queries of SQL (select, where, distinct, order by)
PLO CLO LL
Objectives: 5 1 P2
Understand use of basic queries in SQL Select, From, Where , Distint ,
Order By all related Queries in SQL
The SQL SELECT Statement
SELECT Syntax
Here, column1, column2, are the field names of the table you want to select data from. If you want to select all
the fields available in the table, use the following syntax:
The following SQL statement selects the "CustomerName" and "City" columns from the "Customers" table:
Example
SELECT * Example
The following SQL statement selects all the columns from the "Customers" table:
Example
The WHERE clause is used to extract only those records that fulfill a specified condition.
Page 9 of 2
Database system Lab
Department of Computer Science
SELECT column1, column2, ...
FROM table_name
WHERE condition;
The following SQL statement selects all the customers from the country "Mexico", in the "Customers" table:
Example
Example
SQL requires single quotes around text values (most database systems will also allow double quotes).
Example
The SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only want to list the
different (distinct) values.
The SELECT DISTINCT statement is used to return only distinct (different) values.
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending
order, use the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, ... FROM table_name
Page 10 of
2
Database system Lab
Department of Computer Science
ORDER BY column1, column2, ... ASC|DESC;
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by the "Country"
column:
Example
Lab Task
Task 01: Perform various queries on the inserted and saved data.
Task 03: Perform various queries on the inserted and saved data.
Page 11 of
2
Database system Lab
Department of Computer Science
CONCLUSION:
___________________________________________________________________________
___________________________________________________________________________
__________________________________________________________________________
RUBRICS:
Instructor Signature
Page 12 of
2
Database system Lab
Department of Computer Science
PRACTICAL NO.04
Operators in SQL
PLO CLO LL
3 1 P2
Objectives:
1. Use of Logical and Relational Operators in SQL.
Operator Description
= Equal to
Page 13 of
2
Database system Lab
Department of Computer Science
SQL Logical Operators
Operator Description
Page 14 of
2
Database system Lab
Department of Computer Science
The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
BETWEEN Example
The following SQL statement selects all products with a price BETWEEN 10 and 20:
Example
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Page 15 of
2
Database system Lab
Department of Computer Science
IN Operator Examples
The following SQL statement selects all customers that are located in "Germany", "France" and "UK":
Example
The following SQL statement selects all customers that are NOT located in "Germany", "France" or "UK":
Example
The following SQL statement selects all customers that are from the same countries as the suppliers:
Example
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards used in conjunction with the LIKE operator:
LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
Page 16 of
2
Database system Lab
Department of Computer Science
WHERE CustomerName LIKE 'a%' Finds any values that starts with "a"
WHERE CustomerName LIKE '%a' Finds any values that ends with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in
any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the
second position
WHERE CustomerName LIKE 'a_%_%' Finds any values that starts with "a"
and are at least 3 characters in
length
WHERE ContactName LIKE 'a%o' Finds any values that starts with "a"
and ends with "o"
The following SQL statement selects all customers with a CustomerName ending with "a":
Example
Page 17 of
2
Database system Lab
Department of Computer Science
LAB TASK:
Task 01: Perform various operations on the fields on the inserted and saved data.
CONCLUSION:
___________________________________________________________________________
___________________________________________________________________________
__________________________________________________________________________
RUBRICS:
Instructor Signature
Database system Lab
Department of Computer Science
PRACTICAL NO.05
Group, having
PLO CLO LL
3 1 P2
Objectives: The objective of this exercise is to get you to
1. AGGREGATE FUNCTIONS:
Aggregate functions allow you to perform a calculation on a set of values to return a single scalar value. The
most common aggregate functions are:
▪ AVG
▪ MIN
▪ SUM
▪ COUNT
▪ STDEV
▪ STDEVP
▪ VAR
▪ VARP
▪ MAX
Note: All the Group function except COUNT ignore null values
1. THE GROUP BY CLAUSE
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into
groups. This GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER
BY clause.
For example:
GROUP BY SupplierID
Database system Lab
Department of Computer Science
3. THE HAVING CLAUSE
The WHERE clause is a row filter, the HAVING clause is a group filter. Only groups for which the HAVING
predicate evaluates to TRUE are returned by the HAVING phase to the next logical query processing phase.
Groups for which the predicate evaluates to FALSE or UNKNOWN are discarded. Because the HAVING clause
is processed after the rows have been grouped, you can refer to aggregate functions in the logical expression.
For example, in the query below, the HAVING clause has the logical expression COUNT(*) > 1, meaning that
the HAVING phase filters only groups (Title) with more than one row. The following fragment of query will
help to retrieve required data:
>1
Aliases provide database administrators, as well as other database users, with the ability to reduce the
amount ofcode required for a query, and to make queries simpler to understand. In addition, aliasing can be
used as an obfuscation technique to protect the real names of database fields.
1.1.ALIASING COLUMNS
SELECT column_name AS alias_name FROM table_name;
1.2.ALIASING TABLES
SELECT column_name(s) FROM table_name AS alias_name;
Lab Tasks:
CONCLUSION:
___________________________________________________________________________
___________________________________________________________________________
__________________________________________________________________________
Database system Lab
Department of Computer Science
RUBRICS:
Instructor Signature
Database system Lab
Department of Computer Science
PRACTICAL NO.06
Command to Alter, add and drop
PLO CLO LL
3 1 P2
Objectives: The objective of this exercise is to get you to know
• Use of Commands to Alter Table, Add or Drop a Column
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an existing
table.
To delete a column in a table, use the following syntax (notice that some database systems
don't allow deleting a column):
To change the data type of a column in a table, use the following syntax:
Now we want to add a column named "DateOfBirth" in the "Persons" table. We use the following SQL
statement:
Notice that the new column, "DateOfBirth", is of type date and is going to hold a date. The data type
specifies what type of data the column can hold. For a complete reference of all the data types available
in MS Access, MySQL, and SQL Server, go to our complete Data Types reference.
Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table.
Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two- or four-
digit format.
Next, we want to delete the column named "DateOfBirth" in the "Persons" table. We use the following
SQL statement:
Instructor Signature
Database system Lab
Department of Computer Science
PRACTICAL NO.07
Delete and truncate table.
PLO CLO LL
5 1 P2
Task 01: Create a new table, add data in it and then apply these queries.
Database system Lab
Department of Computer Science
CONCLUSION:
___________________________________________________________________________
___________________________________________________________________________
__________________________________________________________________________
RUBRICS:
Instructor Signature
Database system Lab
Department of Computer Science
PRACTICAL NO.08
Joins in SQL server
PLO CLO LL
5 1 P2
Objectives:
2. JOINS SYNTAX:
SELECT ColumnName(s) FROM Table_1,Table_2 OR
SELECT ColumnName(s)
FROM Table_1 CROSS JOIN Table_2
SELECT column_name(s)
FROM table1 INNER JOIN/ CROSS JOIN/ NATURAL JOIN/ LEFT JOIN/ RIGHT JOIN/ FULL OUTER
JOIN table2
ON table1.column_name = table2.column_name;
What to Submit:
CONCLUSION:
___________________________________________________________________________
___________________________________________________________________________
__________________________________________________________________________
RUBRICS:
Instructor Signature
Database system Lab
Department of Computer Science
PRACTICAL NO.09
Sub Queries
PLO CLO LL
5 2 P4
Objective:
• Understanding of Subqueries.
1.Subquery:
A subquery is a query that is nested inside a SELECT, INSERT, UPDATE, or DELETE statement, or inside
another subquery. A subquery can be used anywhere an expression is allowed.
A subquery nested in the outer SELECT statement has the following components:
• A regular SELECT query including the regular select list components.
• A regular FROM clause including one or more table or view names.
• An optional WHERE clause.
• An optional GROUP BY clause.
• An optional HAVING clause.
The SELECT query of a subquery is always enclosed in parentheses. It cannot include a COMPUTE or
FORBROWSE clause, and may only include an ORDER BY clause when a TOP clause is also specified.
A subquery can be nested inside the WHERE or HAVING clause of an outer SELECT, INSERT, UPDATE,
or DELETE statement, or inside another subquery. Up to 32 levels of nesting is possible, although the limit
varies based on available memory and the complexity of other expressions in the query. Individual queries may
not support nesting up to 32 levels. A subquery can appear anywhere an expression can be used, if it returns a
singlevalue.
If a table appears only in a subquery and not in the outer query, then columns from that table cannot be included
in the output (the select list of the outer query).
In some Transact-SQL statements, the subquery can be evaluated as if it were an independent query.
Conceptually,the subquery results are substituted into the outer query (although this is not necessarily how SQL
Server actuallyprocesses Transact-SQL statements with subqueries). There are three basic types of subqueries.
Those that:
• Operate on lists introduced with IN, or those that a comparison operator modified by ANY or ALL.
• Are introduced with an unmodified comparison operator and must return a single value.
Database system Lab
Department of Computer Science
• Are existence tests introduced with EXISTS.
2. Subquery Rules
• Return customers and their orders, including customers who placed no orders (CustomerID,
OrderID,OrderDate)
• Report only those customer IDs who never placed any order. (CustomerID, OrderID, OrderDate)
• Report those customers who placed orders on July,1997. (CustomerID, OrderID, OrderDate)
• Report the total orders of each customer. (customerID, totalorders)
• Write a query to generate a five copies of each employee. (EmployeeID, FirstName, LastName)
• List all the products whose price is more than average price.
• Find the second highest price of product.
• Write a query that returns a row for each employee and day in the range 04-07-1996 through 04-
08-1997. (EmployeeID, Date)
• Return US customers, and for each customer return the total number of orders and total quantities.
(CustomerID, Totalorders, totalquantity)
• Write a query that returns all customers in the output, but matches them with their respective orders
only if they were placed on July 04,1997. (CustomerID, CompanyName, OrderID, Orderdate)
Are there any employees who are older than their managers?
• List that names of those employees and their ages. (EmployeeName, Age, Manager Age)
Database system Lab
Department of Computer Science
• List the names of products which were ordered on 8th August 1997. (ProductName, OrderDate)
• List the addresses, cities, countries of all orders which were serviced by Anne and were shipped
late.(Address, City, Country)
• List all countries to which beverages have been shipped. (Country)
What to Submit:
CONCLUSION:
___________________________________________________________________________
___________________________________________________________________________
__________________________________________________________________________
RUBRICS:
Instructor Signature
Database system Lab
Department of Computer Science
PRACTICAL NO.10
Single row functions
PLO CLO LL
5 2 P4
Objectives:
The objective of this exercise is to get you familiar with
To apply Single Row functions in SQL.
SQL Functions optionally take arguments from the user and mandatorily return a value. On a broader category, there are two types of
functions:-
Single Row functions - Single row functions are the one who work on single row and return one output per row.
For example, length and case conversion functions are single row functions.
Multiple Row functions - Multiple row functions work upon group of rows and return one result for the complete
set of rows. They are also known as Group Functions.
Single row functions
Single row functions can be character functions, numeric functions, date functions, and conversion functions.
Note that these functions are used to manipulate data items. These functions require one or more input arguments
and operate on each row, thereby returning one output value for each row. Argument can be a column, literal or
an expression. Single row functions can be used in SELECT statement, WHERE and ORDER BY clause. Single
row functions can be -
• General functions - Usually contains NULL handling functions. The functions under the category are
NVL, NVL2, NULLIF, COALESCE, CASE, DECODE.
• Case Conversion functions - Accepts character input and returns a character value. Functions under
the category are UPPER, LOWER and INITCAP.
o INITCAP function converts only the initial alphabets of a string to upper case.
• Character functions - Accepts character input and returns number or character value. Functions under
the category are CONCAT, LENGTH, SUBSTR, INSTR, LPAD, RPAD, TRIM and REPLACE.
o SUBSTR function returns a portion of a string from a given start point to an end point.
o TRIM function trims the string input from the start or end.
o REPLACE function replaces characters from the input string with a given character.
• Date functions - Date arithmetic operations return date or numeric values. Functions under the
category are MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY, LAST_DAY, ROUND and TRUNC.
o MONTHS_BETWEEN function returns the count of months between the two dates.
o LAST_DAY function returns last day of the month of the input date.
o ROUND and TRUNC functions are used to round and truncates the date value.
• Number functions - Accepts numeric input and returns numeric values. Functions under the category
are ROUND, TRUNC, and MOD.
o ROUND and TRUNC functions are used to round and truncate the number value.
o MOD is used to return the remainder of the division operation between two
FROM employees
The SELECT query below demonstrates the use of case conversion functions.
SELECT UPPER (first_name), INITCAP (last_name), LOWER (job_id)
Database system Lab
FROM employees Department of Computer Science
Character functions
CONCAT(FIRST_NAME,LAST_NAME)
EllenAbel
SundarAnde
MozheAtkinson
DavidAustin
The SELECT query below demonstrates the use of SUBSTR and INSTR functions. SUBSTR function returns the
portion of input string from 1st position to 5th position. INSTR function returns the numeric position of character 'a' in
the first name.
FROM employees
SUBST INSTR(FIRST_NAME,'A')
Ellen 0
Sunda 5
Mozhe 0
David 2
Database system Lab
Department of Computer Science
The SELECT query below demonstrates the usage of LPAD and RPAD to pretty print the employee and job
information.
SELECT RPAD(first_name,10,'_')||LPAD (job_id,15,'_')
FROM employees
WHERE rownum < 5;
RPAD(FIRST_NAME,10,'_')||
Steven AD_PRES
Neena AD_VP
Lex AD_VP
Alexander IT_PROG
Number functions
The SELECT query below demonstrates the use of ROUND and TRUNC functions.
SELECT ROUND (1372.472,1)
FROM dual; ROUND(1372.472,1)
______________
1372.5
SELECT TRUNC (72183,-2)
FROM dual;
TRUNC(72183,-2)
________________
72100
employees
101 2871.61877
102 4583.61877
103 2767.61877
SELECT ADD_MONTHS (sysdate, 5), NEXT_DAY (sysdate), LAST_DAY (sysdate) FROM dual;
Task 01: Perform single row functions as discussed in class and check output.
CONCLUSION:
___________________________________________________________________________
___________________________________________________________________________
__________________________________________________________________________
RUBRICS:
Instructor Signature
Database system Lab
Department of Computer Science
PRACTICAL NO.11
Stored Procedure
PLO CLO LL
5 2 P4
Objective:
• Understanding of Stored Procedure
Helping Material:
A SQL stored procedure (SP) is a collection of SQL statements and sql command logic, which is compiled and stored on the
database. Stored procedures in SQL allow us to create SQL queries to be stored and executed on the server. Stored
procedures can also be cached and reused. The main purpose of stored procedures is to hide direct SQL queries from the
code and improve performance of database operations such as select, update, and delete data.
• Types of stored procedures
There are two types of stored procedures available in SQL Server:
I. User defined stored procedures
II. System stored procedures
• User defined stored procedures
User defined stored procedures are created by database developers or database administrators. These SPs contain one more
SQL statements to select, update, or delete records from database tables. User defined stored procedure can take input
parameters and return output parameters. User defined stored procedure is mixture of DDL (Data Definition Language) and
DML (Data Manipulation Language) commands.
T-SQL stored procedures: T-SQL (Transact SQL) SPs receive and return parameters. These SPs process the Insert, Update
and Delete queries with or without parameters and return data of rows as output. This is one of the most common ways to
write SPs in SQL Server.
CLR stored procedures: CLR (Common Language Runtime) SPs are written in a CLR based programming language such
as C# or VB.NET and are executed by the .NET Framework.
Let's login to our SQL Server database, so we can achieve the following:
• How to create a SELECT QUERY based stored procedure which return all records?
• How to create a PARAMETER based SELECT QUERY stored procedure which return records based on
parameters?
• How to create an INSERT query based stored procedure?
• How to create an UPDATE query based stored procedure?
• How to create a DELETE query based stored procedure?
The empty template created by SQL Server for a SP looks like the following. The CREATE PROCEDURE SQL command is
used to create a procedure, followed by a SP name and its parameters. The BEGIN and END area is used to define the query
for the operation. This is where you will write a select, update, insert, or delete queries.
2. -- Template generated from Template Explorer using:
Database system Lab
Department of Computer Science
3. -- Create Procedure (New Menu).SQL
4. --
5. -- Use the Specify Values for Template Parameters
6. -- command (Ctrl-Shift-M) to fill in the parameter
7. -- values below.
8. --
9. -- This block of comments will not be included in
10. -- the definition of the procedure.
11. -- ================================================
12. SET ANSI_NULLS ON
13. GO
14. SET QUOTED_IDENTIFIER ON
15. GO
16. -- =============================================
17. -- Author: <Author,,Name>
18. -- Create date: <Create Date,,>
19. -- Description: <Description,,>
20. -- =============================================
21. CREATE PROCEDURE <Procedure_Name, sysname, ProcedureName>
22. -- Add the parameters for the stored procedure here
23. <@Param1, sysname, @p1> <Datatype_For_Param1, , int> = <Default_Value_For_Param1, , 0>,
24. <@Param2, sysname, @p2> <Datatype_For_Param2, , int> = <Default_Value_For_Param2, , 0>
26. BEGIN
27. -- SET NOCOUNT ON added to prevent extra result sets from
28. -- interfering with SELECT statements.
29. SET NOCOUNT ON;
30.
31. -- Insert statements for procedure here
32. SELECT <@Param1, sysname, @p1>, <@Param2, sysname, @p2>
33. END
34. GO
What is the naming convention for stored procedures?
We must follow standard naming conventions which may also depend on your project and coding policies.
For user defined stored procedure naming conventions, my suggestions are to add one of the following prefixes
to your SP names.
1. sp
2. stp
3. stp_
4. udstp
5. udstp_
Naming conventions are just to identify objects. By adding these prefixes in the name, we can clearly identify
that this object is a stored procedure.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Manoj Kalla
-- Create date: 18th Nov 2017
-- Description: Return all members
-- =============================================
--Store procedure name is --> stpGetAllMembers
CREATE PROCEDURE stpGetAllMembers
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
Database system Lab
Department of Computer Science
SET NOCOUNT ON;
OUTPUT
Database system Lab
Department of Computer Science
In the previous steps, we created a simple SP that returned all rows from a table. Now, let's create a new SP that will
take a city name as an input parameter and will return all rows where city name matches the input parameter value.
Here is the updated SP with a parameter @CityName.
1. SET ANSI_NULLS ON
2. GO
3. SET QUOTED_IDENTIFIER ON
4. GO
5. -- =============================================
6. -- Author: Manoj Kalla
7. -- Create date: 20-Nov-2017
8. -- Description: Return specifc city records
9. -- =============================================
10. CREATE PROCEDURE stpGetMembersByCityName
11. -- Add the parameters for the stored procedure here
12. @CityName nvarchar(30)
13.
14. AS
15. BEGIN
16. -- SET NOCOUNT ON added to prevent extra result sets from
17. -- interfering with SELECT statements.
Database system Lab
Department of Computer Science
18. SET NOCOUNT ON;
19.
20. Select * From tblMembers
21. where MemberCity like '%'+@CityName+'%'
22.
23. END
24. GO
Execute it.
To run this SP, type the following command in SQL query tool:
EXEC GetMemberByCityName @CityName = 'mal'
OR from the UI, run the SP and provide the following input.
Output
1. SET ANSI_NULLS ON
2. GO
3. SET QUOTED_IDENTIFIER ON
4. GO
5. -- =============================================
6. -- Author: Manoj Kalla
7. -- Create date: 20-Nov-2047
8. -- Description: To create a new member
9. -- =============================================
10. CREATE PROCEDURE stpInsertMember
11. @MemberName varchar(50),
12. @MemberCity varchar(25),
13. @MemberPhone varchar(15)
14.
15. AS
16. BEGIN
17. -- SET NOCOUNT ON added to prevent extra result sets from
18. -- interfering with SELECT statements.
19. SET NOCOUNT ON;
20.
21. Insert into tblMembers (MemberName,MemberCity,MemberPhone)
Database system Lab
Department of Computer Science
22. Values (@MemberName,@MemberCity, @MemberPhone)
23.
24. END
25. GO
Pass the value of parameter in Execute dialog box. Something like this:
Database system Lab
Department of Computer Science
Output
In the query window, you can check if a new record for Member Name 'Mahesh Chand' is added to the
table.
Database system Lab
Department of Computer Science
EXEC stpInsertMember @MemberName = 'Suhana & Ashish Kalla ', @MemberCity = 'Mumbai ',
@MemberPhone = N'9022592774xxx'
OUTPUT
You can check “Suhana & Ashish Kalla” record is added successfully.
Database system Lab
Department of Computer Science
1. SET ANSI_NULLS ON
2. GO
3. SET QUOTED_IDENTIFIER ON
4. GO
5. -- =============================================
6. -- Author: Manoj Kalla
7. -- Create date: 20-Nov-2017
8. -- Description: Update a member detail by ID
9. -- =============================================
10. CREATE PROCEDURE stpUpdateMemberByID
11. @MemberID int,
12. @MemberName varchar(50),
13. @MemberCity varchar(25),
14. @MemberPhone varchar(15)15.
16. AS
17. BEGIN
18. -- SET NOCOUNT ON added to prevent extra result sets from
19. -- interfering with SELECT statements.
20. SET NOCOUNT ON;21.
22. UPDATE tblMembers
23. Set MemberName = @MemberName,
24. MemberCity = @MemberCity,
25. MemberPhone = @MemberPhone
26. Where MemberID = @MemberID
27. END
28. GO
Right click on the stored procedure in the Object Explorer and select Refresh. You will see the SP is created.
Now, Right click on SP name and select Execute stored procedure…. Provide the input values and execute.
Database system Lab
Department of Computer Science
1. USE [MBKTest]
2. GO
3.
4. DECLARE @return_value int
5.
6. EXEC @return_value = [dbo].[stpUpdateMemberByID]
7. @MemberID = 20,
8. @MemberName = N'Nirupama Kalla',
9. @MemberCity = N'Mumbai',
10. @MemberPhone = N'904512541xxxx'
11.
12. SELECT 'Return Value' = @return_value
13.
14. GO
Database system Lab
Department of Computer Science
EXEC stpUpdateMemberByID 17,'Gopal Madhavrai','Bikaner','90454564xxx'
The results should show you the updated values.
Execute it.
Right click on Stored Procedures in the Object Explorer and select Refresh.
RUN stored procedure BY UI
Now again right click on stored procedure and select Execute stored procedure…
As you can see in the image, I passed @MemberID parameter value = 4.
Database system Lab
Department of Computer Science
OUTPUT
You can see in image MemberID = 4 record has been deleted successfully.
In this article, we saw how to create stored procedures in a SQL Server database for inserting, updating, anddeleting
Database system Lab
Department of Computer Science
records.
Modifying the stored procedure
ALTER PROCEDURE GetProductDescAS
RUBRICS:
Instructor Signature
Database system Lab
Department of Computer Science
-PRACTICAL NO.12
Understanding of Triggers
PLO CLO LL
5 2 P4
Objective:
Understanding of Triggers
Introduction:
A Trigger in Structured Query Language is a set of procedural statements which are executed automatically when
there is any response to certain events on the table in the database. Triggers are used to protect the data integrity
in the database.
In SQL, this concept is the same as the trigger in real life. For example, when we pull the gun trigger, the bullet is
fired.
The trigger is always executed with the specific table in the database. If we remove the table, all the triggers
associated with that table are also deleted automatically.
In Structured Query Language, triggers are called only either before or after the below events:
1. INSERT Event: This event is called when the new row is entered in the table.
2. UPDATE Event: This event is called when the existing record is changed or modified in the table.
3. DELETE Event: This event is called when the existing record is removed from the table.
Types of Triggers in SQL
In the trigger syntax, firstly, we have to define the name of the trigger after the CREATE TRIGGER keyword. After
that, we have to define the BEFORE or AFTER keyword with anyone event.
After the table name, we have to define the row-level or statement-level trigger
The following query creates the Student_Trigger table in the SQL database:
Student_EnglishMarks INT,
Student_PhysicsMarks INT,
Student_ChemistryMarks INT,
Student_MathsMarks INT,
Student_TotalMarks INT,
Student_Percentage );
The following query fires a trigger before the insertion of the student record in the table:
CREATE TRIGGER
Student_Table_Marks
BEFORE INSERT
ON
Student_Trigger
FOR EACH ROW
SET new.Student_TotalMarks = new.Student_EnglishMarks + new.Student_PhysicsMarks +
new.Student_Chemist ryMarks + new.Student_MathsMarks,
new.Student_Percentage = (
Student_Trigger table:
Output:
Following are the three main advantages of triggers in Structured Query Language:
1. SQL provides an alternate way for maintaining the data and referential integrity in the
tables.
2. Triggers helps in executing the scheduled tasks because they are called automatically.
3. They catch the errors in the database layer of various businesses.
4. They allow the database users to validate values before inserting and updating.
Disadvantages of Triggers in SQL
LAB TASK :
59
Database system Lab
Department of Computer Science
CONCLUSION:
____________________________________________________________
____________________________________________________________
____________________________________________________________
____________________________________________
RUBRICS:
Instructor Signature
60
Database system Lab
Department of Computer Science
PRACTICAL NO.13
Views and its types in SQL Server
PLO CLO LL
5 2 P4
Learning Objectives:
To understand views and its types in SQL.
SQL CREATE VIEW Statement
A view contains rows and columns, just like a real table. The fields in a view are fields
from one or more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the
data as if the data were coming from one single table.
If you have the Northwind database you can see that it has several views installed by default.
The view "Current Product List" lists all active products (products that are not
discontinued) from the "Products" table. The view is created with the following SQL:
CREATE VIEW
[Current Product List]
AS SELECT
ProductID,
ProductName
FROM Products
WHERE Discontinued = No;
61
Database system Lab
Department of Computer Science
Another view in the Northwind sample database selects every product in the "Products"
table with a unit price higher than the average unit price:
CREATE VIEW [Products
Above Average Price] AS
SELECT ProductName,
UnitPrice
FROM Products
WHERE UnitPrice > (SELECT
Another view in the Northwind database calculates the total sale for each category in
1997. Note that this view selects its data from another view called "Product Sales for
1997":
Now we want to add the "Category" column to the "Current Product List" view. We will update the
view with the following SQL:
62
Database system Lab
Department of Computer Science
CREATE OR REPLACE VIEW [Current Product List] AS SELECT ProductID, ProductName,
Category
FROM Products
WHERE Discontinued = No;
LAB TASK:
CONCLUSION:
____________________________________________________________
____________________________________________________________
____________________________________________________________
____________________________________________
RUBRICS:
Instructor Signature
63
Database system Lab
Department of Computer Science
PRACTICAL NO.14
CRUD operations
PLO CLO LL
5 2 P4
Learning Objectives:
• CRUD operations using C# language with SQL server
FROM table_name;
64
Database system Lab
Department of Computer Science
cmd.Parameters.AddWithValue("@ID", int.Parse(textBox1.Text));
cmd.Parameters.AddWithValue("@Name", textBox2.Text);
cmd.Parameters.AddWithValue("@Department",
textBox3.Text); cmd.ExecuteNonQuery();
MessageBox.Show("Successfully saved");
var con =
Configuration.getInstance().getConnection();
SqlCommand cmd = new SqlCommand("Select *
from Table_1", con); SqlDataAdapter da = new
SqlDataAdapter(cmd);
DataTable dt =
new
DataTable();
da.Fill(dt);
dataGridView1.D
ataSource = dt;
Lab Tasks
65
Database system Lab
Department of Computer Science
CONCLUSION:
____________________________________________________________
____________________________________________________________
____________________________________________________________
____________________________________________
RUBRICS:
Instructor Signature
66