SlideShare a Scribd company logo
1 of 165
Download to read offline
Database Management System
Lab Manual
Engr. Syed Zaid Irshad
This document contains Lab Theory and Tasks
It is up to the instructor how he/she divides tasks among each Labs
Department of Computer Science
Mohammad Ali Jinnah University, Karachi
Pakistan
January 11, 2023
2
Contents
1 Visual Studio 5
1.1 About Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.1.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.1.2 History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.1.3 Why you should choose Visual Studio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3 Simple Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.4 Simple Countdown Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.5 User Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2 SQL Server & SQL Server Management Studio 27
2.1 About Software’s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.1.1 Version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.1.2 Edition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.1.3 Key Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.2 Basics of SQL Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.2.1 Statement Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.2.2 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.2.3 Predicates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.2.4 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.2.5 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.2.6 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.2.7 Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.3 Levels of Severity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.4 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.5 Create New Login . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3 Transact-SQL Statements (Basic) 45
3.1 Load Data-set on SQL Server Management Studio . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.2 DML (Data Manipulation Language) Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
3.3 Data Definition Language (DDL) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
3.3.1 Procedure/Variables for Existing Database . . . . . . . . . . . . . . . . . . . . . . . . . . 78
3.3.2 Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
3.3.3 Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
3.3.4 Column . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
4 School Management System 91
4.1 ER-Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
4.2 Database Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
4.3 User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
5 Transact-SQL Statements (Intermediate) 117
5.1 Joins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
5.2 Variables and Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
5.3 Sub-queries and Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
5.4 Program Flow Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
5.5 Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
5.6 Triggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
3
4 CONTENTS
6 Malicious 147
6.1 Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
6.2 Create Setup File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
A Lab Details 165
Chapter 1
Visual Studio
1.1 About Software
• Visual Studio is an integrated development environment (IDE) from Microsoft.
• It is used to develop computer programs, as well as websites, web apps, web services and mobile apps.
• Visual Studio uses Microsoft software development platforms such as Windows API, Windows Forms,
Windows Presentation Foundation, Windows Store and Microsoft Silverlight.
• It can produce both native codes and managed code.
• Visual Studio includes a code editor supporting IntelliSense (the code completion component) as well as
code refactoring.
• The integrated debugger works both as a source-level debugger and a machine-level debugger.
• Other built-in tools include a code profiler, a designer for building GUI applications, a web designer, a
class designer, and a database schema designer.
• It accepts plug-ins that expand the functionality at almost every level—including adding support for source
control systems (like Subversion and Git) and adding new toolsets like editors and visual designers for
domain-specific languages or toolsets for other aspects of the software development lifecycle (like the Azure
DevOps client: Team Explorer).
• Visual Studio supports 36 different programming languages and allows the code editor and debugger to
support (to varying degrees) nearly any programming language, provided a language-specific service exists.
• Built-in languages include C, Cplusplus, Cplusplus/CLI, Visual Basic .NET, C#, F#, JavaScript,
TypeScript, XML, XSLT, HTML, and CSS.
• Support for other languages such as Python, Ruby, Node.js, and M among others is available via
plug-ins.
• Java (and J#) were supported in the past.
• The most basic edition of Visual Studio, the Community edition, is available free of charge. The slogan for
Visual Studio Community edition is ”Free, fully-featured IDE for students, open-source and individual
developers”.
1.1.1 Features
Visual Studio provides the most advanced features that the latest developers are looking for. A few of the most
important features are described as follows:
1. Code Editor: Visual Studio has the best-in-class Code editor which supports multiple functionalities. It
enables bookmarks in code to incorporate Quick Navigation. In addition to the normal text, VS also
provides Incremental Search, Regex Search, Multi-item Clipboard, and Task-list. The Editor is also capable
to support Code refactoring, Parameter Reordering, Variable and Method Renaming, Interface Extraction
and many more user-friendly functionalities.
5
6 CHAPTER 1. VISUAL STUDIO
2. Debugger: The remarkable Debugger of MS Visual Studio can work both as a Machine Level Debugger as
well as a Source Level Debugger. It is capable to debug Mapped Code as well as Native Code. It is capable
to compile any programming language that supports VS. It is capable to attach itself to the currently
running process to conduct monitoring and debugging procedures on the code, provided the source code is
available. VS can incorporate Memory Dumps and Multi-threading as well.
3. Designer: Visual Studio includes several visual designers to help with the development of applications.
Some of the tools are listed below.
(a) WPS authorizes user interfaces for Windows Presentation Foundation.
(b) Windows Forms designer creates GUI applications using Windows Forms.
(c) The Class Designer authorises and edits the classes including its members and their access using UML
modelling.
(d) Visual Studio additionally includes a website editor and designer that permits websites to be authored
by dragging and dropping widgets.
(e) Mapping designer is employed by LINQ to SQL to design the mapping between information schema
and therefore the classes that encapsulate the data.
(f) The data designer is used to graphically edit information schema, as well as written tables, primary
and foreign keys and constraints.
4. Other Tools
(a) Properties editor edits the properties in the GUI in VS.
(b) It enlists all the properties available for classes, objects, and web pages.
(c) Server Explorer manages Database connections on a computer.
(d) Object browser is used to browse the namespaces in managed assemblies.
(e) Team Explorer Integrates the Axure DevOps Into the VS IDE.
(f) Data Explorer manages MS SQL databases and instances.
(g) Solution Explorer manages and browses the files in a solution.
5. Extensibility Visual Studio permits developers to write down extensions for Visual Studio to extend its
capabilities. These extensions “plug into” Visual Studio and extend its functionality. Extensions are
available in the form of macros, add-ins, and packages.
1.1.2 History
Product name Code name Release date Support Ends
Visual Studio 2022 Dev17 08/11/2021 January 13, 2032
Visual Studio 2019 Dev16 02/04/2019 April 10, 2029
Visual Studio 2017 Dev15 07/03/2017 April 13, 2027
Visual Studio 2015 Dev14 20/07/2015 October 14, 2025
Visual Studio 2013 Dev12 17/10/2013 April 9, 2024
Visual Studio 2012 Dev11 12/09/2012 January 10, 2023
Visual Studio 2010 Dev10 12/04/2010 July 14, 2020
Visual Studio 2008 Orcas 19/11/2007 April 10, 2018
Visual Studio 2005 Whidbey 07/11/2005 April 12, 2016
Visual Studio .NET 2003 Everett 24/04/2003 October 8, 2013
Visual Studio .NET (2002) Rainier 13/02/2002 July 14, 2009
Visual Studio 6.0 Aspen 02/09/1998 September 30, 2005
Visual Studio 97 Boston 19/03/1997 June 30, 2003
1.1.3 Why you should choose Visual Studio
• Visual Studio is functionally feature-rich. In most cases, Visual Code matches the requirements of most
developers perfectly without having to rely on further extensions or plugins.
1.2. INSTALLATION 7
• In Visual Studio, collaborating with your entire team is pretty easy when it comes to development as well
as debugging code. The workflow is super-smooth and is loaded with all kinds of features one would need
in the long run.
• When it comes to heavy-duty code analysis, debugging as well as performance profiling, Visual Studio is
an incredible option.
• Visual Studio is pretty commonly used in the game development industry. For instance, UNITY, a
multi-platform environment integrated with Visual Studio, can work effortlessly to build cross-platform
mobile gaming applications, AR/VR applications, and more!
Organizations using Visual Studio for development
Useful Link for Students: https://visualstudio.microsoft.com/students/
1.2 Installation
1. Download software from the link.
8 CHAPTER 1. VISUAL STUDIO
2. Open the software by double-clicking on it.
3. Select ASP.NET and web development, Data Storage and Processing, and .Net Desktop Development from
Workloads.
1.2. INSTALLATION 9
4. Select .Net 6.0 Runtime, .Net Core 3.1 Runtime (LST), .Net Framework 4.6.2 targeting pack, and .Net
Framework 4.7 targeting pack from Individual Components. Press the Install button on the bottom right
corner. Wait for the installation to complete.
5. Press the Launch button.
10 CHAPTER 1. VISUAL STUDIO
6. Sign in using your Microsoft account.
7. Select Development Settings to General. Choose a Theme colour if you wish. Press Start Visual Studio
Button.
1.3. SIMPLE APPLICATION 11
1.3 Simple Application
1. Open Visual Studio, Select Create a new Project
2. Choose Windows Form Application (.NET Framework), Press Next
12 CHAPTER 1. VISUAL STUDIO
3. Type Name and press Create
4. Select Textbox and Button from Common Control in Toolbox
1.3. SIMPLE APPLICATION 13
5. Rename Button and Double click on it.
6. type: MessageBox.Show(textBox1.Text); in button1 Click
14 CHAPTER 1. VISUAL STUDIO
7. Press Start from Ribbon
8. Type String and Press Button
1.4. SIMPLE COUNTDOWN APPLICATION 15
1.4 Simple Countdown Application
1. Open Visual Studio, Select Create a new Project, Choose Windows Form Application (.NET Framework),
Press Next
2. Type Name and press Create
16 CHAPTER 1. VISUAL STUDIO
3. Select Textbox and 2 Buttons from Common Control in Toolbox
4. Rename Buttons (Start, Pause) and Double click on them.
1.4. SIMPLE COUNTDOWN APPLICATION 17
5. Search Timer in Toolbox and add it to the project.
6. Type Following Code in .cs file
namespace CountdownTimer {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
int second;
private void button1_Click(object sender, EventArgs e) {
timer1.Start();
}
private void button3_Click(object sender, EventArgs e) {
timer1.Stop();
label2.Text = "Paused";
}
private void timer1_Tick(object sender, EventArgs e) {
if (second > 0) {
second = second - 1;
label2.Text = second.ToString() + " Second(s)";
} else {
timer1.Stop();
label2.Text = "Times Up";
}
}
private void textBox3_TextChanged(object sender, EventArgs e) {
second = Convert.ToInt32(textBox3.Text);
}
}
}
18 CHAPTER 1. VISUAL STUDIO
7. Press Start from Ribbon, Type Time and Press Start Button
1.5 User Information
1. Open Visual Studio, Select Create a new Project
1.5. USER INFORMATION 19
2. Choose Windows Form Application (.NET Framework), Press Next
3. Type Name and press Create
20 CHAPTER 1. VISUAL STUDIO
4. Change the form’s name from ”Form1.cs” to ”UserInfo.cs”.
5. Clicking the form’s title bar, navigate to the Properties window and set the Size property’s Width to 455
and Height to 251.
1.5. USER INFORMATION 21
6. Drag a Label control onto the form; select this control, navigate to the Properties window, and set the
Name property to CountryLabel, AutoSize property to false, Location property’s X to 12 and Y to 26,
Size property’s Width to 71 and Height to 15, Text property to Enter Country.
7. Drag a TextBox control in front of the Country label. Select this control, navigate to the Properties
window, and set the Name property to Country, Location property’s X to 97 and Y to 19, Size property’s
Width to 129 and Height to 23.
22 CHAPTER 1. VISUAL STUDIO
8. Drag another Label below Country, select this control, navigate to the Properties window, and set the
Name property to StateLabel, the AutoSize property to false, the Location property’s X to 12 and Y to 65,
Size property’s Width to 60 and Height to 15, Text property to Enter State.
9. Drag a TextBox control in front of the State label. Select this control, navigate to the Properties window,
and set the Name property to State, Location property’s X to 97 and Y to 58, Size property’s Width to
129 and Height to 23.
1.5. USER INFORMATION 23
10. Drag a ListBox control onto the UserInfo form on the right side of the TextBox control you have added.
Select this control, navigate to the Properties window, and set the Name property to CountryList, Location
property’s X to 280 and Y to 12, Size property’s Width to 129 and Height to 79.
11. Drag a ComboBox below the ListBox that you just added. Select this control, navigate to the Properties
window, and set the Name property to StateCB, Location property’s X to 280 and Y to 117, Size property’s
Width to 129 and Height to 23.
24 CHAPTER 1. VISUAL STUDIO
12. Drag two CheckBoxes below the Label controls, and name them PostalMail (location 97, 117) and Email
(location 97, 142); set their Text property to Postal Mail and E-Mail, respectively.
13. Drag two RadioButtons below the TextBox controls, and name Male (location 97, 178) and Female (location
97, 203); set their Text property to Male and Female, respectively.
1.5. USER INFORMATION 25
14. Drag a Button control to the UserInfo form to the left side below the CheckBox controls; select this control,
navigate to the Properties window, and set the Name property to Add, Location property’s X to 65 and Y
to 88, Size property’s Width to 95 and Height to 23, Text property to Add.
15. Drag a Button control next to the Add button; select this control, navigate to the Properties window, and
set the Name property to RemoveCountry, Location property’s X to 166 and Y to 87, Size property’s
Width to 95 and Height to 23, Text property to Remove Country.
26 CHAPTER 1. VISUAL STUDIO
16. Drag a Button control, navigate to the Properties window, and set the Name property to ShowDetails,
Location property’s X to 415 and Y to 117, Size property’s Width to 90 and Height to 23, Text property
to Show Details.
17. Type the following Code in the .cs file
namespace UserInformation {
public partial class UserInfo : Form {
public UserInfo() {
InitializeComponent();
}
private void addCountry_Click(object sender, EventArgs e) {
CountryList.Items.Add(Country.Text);
Country.Clear();
StateCB.Items.Add(State.Text);
State.Clear();
}
private void RemoveCountry_Click(object sender, EventArgs e) {
CountryList.Items.Remove(CountryList.SelectedItem);
}
private void showDetail_Click(object sender, EventArgs e) {
if (Email.Checked == true || Postmail.Checked == true &&
male.Checked == true) {
MessageBox.Show("Hello Mr, you will be contacted by either
USPS or email", "Information",MessageBoxButtons.OKCancel,
MessageBoxIcon.Information);
}
else
if (Email.Checked == true || Postmail.Checked == true &&
female.Checked == true) {
MessageBox.Show("Hello Mam, you will be contacted by either USPS
or email", "Information",MessageBoxButtons.OKCancel,
MessageBoxIcon.Information);
}
}
}
}
Chapter 2
SQL Server & SQL Server Management
Studio
2.1 About Software’s
• Microsoft SQL Server is a relational database management system developed by Microsoft.
• As a database server, it is a software product with the primary function of storing and retrieving data
as requested by other software applications—which may run either on the same computer or on another
computer across a network (including the Internet).
• Microsoft markets at least a dozen different editions of Microsoft SQL Server, aimed at different audiences
and for workloads ranging from small single-machine applications to large Internet-facing applications with
many concurrent users.
• SQL Server Management Studio (SSMS) is an IDE that provides a graphical interface for connecting and
working with MS SQL server.
• It was launched with Microsoft SQL Server 2005 and is used for configuring, managing, and administering
all components within Microsoft SQL Server.
2.1.1 Version
• SQL Server
– Microsoft and Sybase released version 1.0 in 1989.
– However, the partnership between these two ended in the early 1990s.
– Microsoft maintained ownership rights to the name SQL Server.
– Since the 1990s, subsequent versions of SQL Server have been released including SQL Server 2000,
2005, 2008, 2012, 2014, 2016, 2017, and 2019.
• SQL Server Management Studio
– SSMS first version was with SQL server 2005.
– SSMS remains an integral part of SQL server with SQL Server 2008, SQL Server 2012 and SQL Server
2016.
– In 2016, Microsoft started the first numerical series of versioning with the SSMS version number 16.3.
– All series include 16.x, 17.x and 18.0 as version numbers.
2.1.2 Edition
• SQL Server
– SQL Server Enterprise: It is used in high-end, large scale and mission-critical businesses. It provides
High-end security, Advanced analytics, Machine Learning, etc.
27
28 CHAPTER 2. SQL SERVER & SQL SERVER MANAGEMENT STUDIO
– SQL Server Standard: It is suitable for Mid-Tier Applications and Data Marts. It includes basic
reporting and analytics.
– SQL Server WEB: It is designed for a low total cost-of-ownership option for Web hosters. It provides
scalability, affordability, and manageability capabilities for small to large-scale Web properties.
– SQL Server Developer: It is similar to an enterprise edition for the non-production environment. It is
mainly used for build, testing, and demoing.
– SQL Server Express: It is for small-scale applications and is free to use.
2.1.3 Key Components
• SQL Server
– Database Engine: This component handle storage, Rapid transaction Processing, and Securing Data.
– SQL Server: This service starts, stops, pauses, and continues an instance of Microsoft SQL Server.
The executable name is sqlservr.exe.
– SQL Server Agent: It performs the role of Task Scheduler. It can be triggered by any event or as per
demand. The executable name is sqlagent.exe.
– SQL Server Browser: This listens to the incoming request and connects to the desired SQL server
instance. The executable name is sqlbrowser.exe.
– SQL Server Full-Text Search: This lets the user run full-text queries against Character data in SQL
Tables. The executable name is fdlauncher.exe.
– SQL Server VSS Writer: This allows backup and restoration of data files when the SQL server is not
running. The executable name is sqlwriter.exe.
– SQL Server Analysis Services (SSAS): Provide Data analysis, Data mining and Machine Learning
capabilities. SQL server is integrated with R and Python language for advanced analytics. The
executable name is msmdsrv.exe.
– SQL Server Reporting Services (SSRS): Provides reporting features and decision-making capabilities.
It includes integration with Hadoop. The executable name is ReportingServicesService.exe.
– SQL Server Integration Services (SSIS): Provided Extract-Transform and Load capabilities of the
different types of data from one source to another. It can be viewed as converting raw information
into useful information. The executable name is MsDtsSrvr.exe.
2.2 Basics of SQL Server
2.2.1 Statement Types
• Data Definition Language (DDL)
– CREATE
– ALTER
– DROP
• Data Manipulation Language (DML)
– SELECT
– INSERT
– UPDATE
– DELETE
• Data Control Language (DCL)
– GRANT
– REVOKE
– DENY
2.2. BASICS OF SQL SERVER 29
2.2.2 Data Types
• String
– char(n) - Fixed width character string
– varchar(n) - Variable width character string
– varchar(max) - Variable width character string
– text - Variable width character string
– nchar - Fixed width Unicode string
– nvarchar - Variable width Unicode string
– nvarchar(max) - Variable width Unicode string
– ntext - Variable width Unicode string
– binary(n) - Fixed width binary string
– varbinary - Variable width binary string
– varbinary(max) - Variable width binary string
– image - Variable width binary string 2GB
• Numeric
– bit - Integer that can be 0, 1, or NULL
– tinyint - Allows whole numbers from 0 to 255
– smallint - Allows whole numbers between -32,768 and 32,767
– int - Allows whole numbers between -2,147,483,648 and 2,147,483,647
– bigint - Allows whole numbers between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807
– decimal(p,s) - Fixed precision and scale numbers.
– numeric(p,s) - Fixed precision and scale numbers.
– smallmoney - Monetary data from -214,748.3648 to 214,748.3647
– money - Monetary data from -922,337,203,685,477.5808 to 922,337,203,685,477.5807
– float(n) - Floating precision number data from -1.79E + 308 to 1.79E + 308.
– real - Floating precision number data from -3.40E + 38 to 3.40E + 38 4 bytes
• Date and Time
– datetime - From January 1, 1753 to December 31, 9999 with an accuracy of 3.33 milliseconds
– datetime2 - From January 1, 0001 to December 31, 9999 with an accuracy of 100 nanoseconds 6-8
bytes
– smalldatetime - From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute
– date - Store a date only. From January 1, 0001 to December 31, 9999
– time - Store a time only to an accuracy of 100 nanoseconds
– datetimeoffset - The same as datetime2 with the addition of a time zone offset
– timestamp - Stores a unique number that gets updated every time a row gets created or modified.
The timestamp value is based upon an internal clock and does not correspond to real-time. Each
table may have only one timestamp variable
2.2.3 Predicates
A predicate is an expression that evaluates to TRUE, FALSE, or UNKNOWN.
• IN - Determines whether a specified value matches any value in a sub-query or a list.
• BETWEEN - Specifies a range of values to test.
30 CHAPTER 2. SQL SERVER & SQL SERVER MANAGEMENT STUDIO
• LIKE - Used to match characters against a specified pattern.
• CONTAINS - Searches for precise or less precise matches to single words and phrases, words within a
certain distance of one another, or weighted matches. ALL TRUE if all of the subquery values meet the
condition
• AND - TRUE if all the conditions separated by AND is TRUE
• ANY - TRUE if any of the subquery values meet the condition
• EXISTS - TRUE if the subquery returns one or more records
• NOT - Displays a record if the condition(s) is NOT TRUE
• OR - TRUE if any of the conditions separated by OR is TRUE
• SOME - TRUE if any of the subquery values meet the condition
2.2.4 Operators
• Arithmetic
– Add (+)
– Subtract (-)
– Multiply (*)
– Divide (/)
– Modulo (%)
• Bitwise
– AND (&)
– OR (|)
– Exclusive OR (∧)
• Comparison
– Equal to (=)
– Greater than (>)
– Less than (<)
– Greater than or equal to (>=)
– Less than or equal to (<=)
– Not equal to (<>)
• Compound
– Add equals (+=)
– Subtract equals (-=)
– Multiply equals (*=)
– Divide equals (/=)
– Modulo equals (%=)
– Bitwise AND equals (&=)
– Bitwise exclusive equals (∧=)
– Bitwise OR equals (| =)
2.2.5 Comments
• Single Line (−−Comment)
• Multi-line (/* Comments */)
2.2. BASICS OF SQL SERVER 31
2.2.6 Functions
• String
– ASCII(character) - The ASCII() function returns the ASCII value for the specific character.
– CHAR(code) - The CHAR() function returns the character based on the ASCII code.
– CHARINDEX(substring, string, start) - The CHARINDEX() function searches for a substring in a
string, and returns the position.
– CONCAT(string1, string2, ...., string n) - The CONCAT() function adds two or more strings together.
– string1 + string2 + string n - The + operator allows you to add two or more strings together.
– CONCAT WS(separator, string1, string2, ...., string n) - The CONCAT WS() function adds two or
more strings together with a separator.
– DATALENGTH(expression) - The DATALENGTH() function returns the number of bytes used to
represent an expression.
– DIFFERENCE(expression, expression) - The DIFFERENCE() function compares two SOUNDEX
values, and returns an integer. The integer value indicates the match for the two SOUNDEX values,
from 0 to 4.
– FORMAT(value, format, culture) - The FORMAT() function formats a value with the specified
format.
– LEFT(string, number of chars) - The LEFT() function extracts a number of characters from a string
(starting from left).
– LEN(string) - The LEN() function returns the length of a string.
– LOWER(text) - The LOWER() function converts a string to lower-case.
– LTRIM(string) - The LTRIM() function removes leading spaces from a string.
– NCHAR(number code) - The NCHAR() function returns the Unicode character based on the number
code.
– PATINDEX(%pattern%, string) - The PATINDEX() function returns the position of a pattern in a
string.
– QUOTENAME(string, quote char) - The QUOTENAME() function returns a Unicode string with
delimiters added to make the string a valid SQL Server delimited identifier.
– REPLACE(string, old string, new string) - The REPLACE() function replaces all occurrences of a
substring within a string, with a new substring.
– REPLICATE(string, integer) - The REPLICATE() function repeats a string a specified number of
times.
– REVERSE(string) - The REVERSE() function reverses a string and returns the result.
– RIGHT(string, number of chars) - The RIGHT() function extracts a number of characters from a
string (starting from the right).
– RTRIM(string) - The RTRIM() function removes trailing spaces from a string.
– SOUNDEX(expression) - The SOUNDEX() function returns a four-character code to evaluate the
similarity of two expressions.
– SPACE(number) - The SPACE() function returns a string of the specified number of space characters.
– STR(number, length, decimals) - The STR() function returns a number as a string.
– STUFF(string, start, length, new string) - The STUFF() function deletes a part of a string and then
inserts another part into the string, starting at a specified position.
– SUBSTRING(string, start, length) - The SUBSTRING() function extracts some characters from a
string.
– TRANSLATE(string, characters, translations) - The TRANSLATE() function returns the string
from the first argument after the characters specified in the second argument are translated into the
characters specified in the third argument.
32 CHAPTER 2. SQL SERVER & SQL SERVER MANAGEMENT STUDIO
– TRIM([characters FROM ]string) - The TRIM() function removes the space character OR other
specified characters from the start or end of a string.
– UNICODE(character expression) - The UNICODE() function returns an integer value (the Unicode
value), for the first character of the input expression.
– UPPER(text) - The UPPER() function converts a string to upper-case.
• Math/Numeric
– ABS(number) - The ABS() function returns the absolute value of a number.
– ACOS(number) - The ACOS() function returns the arc cosine of a number.
– ASIN(number) - The ASIN() function returns the arc sine of a number.
– ATAN(number) - The ATAN() function returns the arc tangent of a number.
– ATN2(a, b) - The ATN2() function returns the arc tangent of two numbers.
– AVG(expression) - The AVG() function returns the average value of an expression.
– CEILING(number) - The CEILING() function returns the smallest integer value that is larger than
or equal to a number.
– COUNT(expression) - The COUNT() function returns the number of records returned by a select
query.
– COS(number) - The COS() function returns the cosine of a number.
– COT(number) - The COT() function returns the cotangent of a number.
– DEGREES(number) - The DEGREES() function converts a value in radians to degrees.
– EXP(number) - The EXP() function returns e raised to the power of a specified number.
– FLOOR(number) - The FLOOR() function returns the largest integer value that is smaller than or
equal to a number.
– LOG(number, base) - The LOG() function returns the natural logarithm of a specified number or the
logarithm of the number to the specified base.
– LOG10(number) - The LOG10() function returns the natural logarithm of a number to base 10.
– MAX(expression) - The MAX() function returns the maximum value in a set of values.
– MIN(expression) - The MIN() function returns the minimum value in a set of values.
– PI() - The PI() function returns the value of PI.
– POWER(a, b) - The POWER() function returns the value of a number raised to the power of another
number.
– RADIANS(number) - The RADIANS() function converts a degree value into radians.
– RAND(seed) - The RAND() function returns a random number between 0 (inclusive) and 1 (exclusive).
– ROUND(number, decimals, operation) - The ROUND() function rounds a number to a specified
number of decimal places.
– SIGN(number) - The SIGN() function returns the sign of a number.
– SIN(number) - The SIN() function returns the sine of a number.
– SQRT(number) - The SQRT() function returns the square root of a number.
– SQUARE(number) - The SQUARE() function returns the square of a number.
– SUM(expression) - The SUM() function calculates the sum of a set of values.
– TAN(number) - The TAN() function returns the tangent of a number.
• Date
– CURRENT TIMESTAMP - The CURRENT TIMESTAMP function returns the current date and
time, in a ’YYYY-MM-DD hh:mm:ss.mmm’ format.
2.2. BASICS OF SQL SERVER 33
– DATEADD(interval, number, date) - The DATEADD() function adds a time/date interval to a date
and then returns the date.
– DATEDIFF(interval, date1, date2) - The DATEDIFF() function returns the difference between two
dates.
– DATEFROMPARTS(year, month, day) - The DATEFROMPARTS() function returns a date from
the specified parts (year, month, and day values).
– DATENAME(interval, date) - The DATENAME() function returns a specified part of a date.
– DATEPART(interval, date) - The DATEPART() function returns a specified part of a date.
– DAY(date) - The DAY() function returns the day of the month (from 1 to 31) for a specified date.
– GETDATE() - The GETDATE() function returns the current database system date and time, in a
’YYYY-MM-DD hh:mm:ss.mmm’ format.
– GETUTCDATE() - The GETUTCDATE() function returns the current database system UTC date
and time, in a ’YYYY-MM-DD hh:mm:ss.mmm’ format.
– ISDATE(expression) - The ISDATE() function checks an expression and returns 1 if it is a valid date,
otherwise 0.
– MONTH(date) - The MONTH() function returns the month part for a specified date (a number from
1 to 12).
– SYSDATETIME() - The SYSDATETIME() function returns the date and time of the computer where
the SQL Server is running.
– YEAR(date) - The YEAR() function returns the year part for a specified date.
• Advance
– CAST(expression AS datatype(length)) - The CAST() function converts a value (of any type) into a
specified datatype.
– COALESCE(val1, val2, ...., valn) - The COALESCE() function returns the first non-null value in a
list.
– CONVERT(data type(length), expression, style) - The CONVERT() function converts a value (of
any type) into a specified datatype.
– CURRENT USER - The CURRENT USER function returns the name of the current user in the SQL
Server database.
– IIF(condition, value if true, value if false) - The IIF() function returns a value if a condition is TRUE,
or another value if a condition is FALSE.
– ISNULL(expression, value) - The ISNULL() function returns a specified value if the expression is
NULL.
– ISNUMERIC(expression) - The ISNUMERIC() function tests whether an expression is numeric.
– NULLIF(expr1, expr2) - The NULLIF() function returns NULL if two expressions are equal, otherwise,
it returns the first expression.
– SESSION USER - The SESSION USER function returns the name of the current user in the SQL
Server database.
– SESSIONPROPERTY(option) - The SESSIONPROPERTY() function returns the session settings
for a specified option.
– SYSTEM USER - The SYSTEM USER function returns the login name for the current user.
– USER NAME(id number) - The USER NAME() function returns the database user name based on
the specified id.
2.2.7 Control Flow
• BEGIN sql statement — statement block END
• BREAK
34 CHAPTER 2. SQL SERVER & SQL SERVER MANAGEMENT STUDIO
• CONTINUE
• IF Boolean expression sql statement — statement block [ ELSE sql statement — statement block ]
• RETURN [ integer expression ]
• THROW [ error number — @local variable , message — @local variable , state — @local variable ]
• BEGIN TRY sql statement — statement block END TRY BEGIN CATCH [ sql statement — state-
ment block ] END CATCH
• WHILE Boolean expression sql statement — statement block — BREAK — CONTINUE
2.3 Levels of Severity
• 0-9: Informational messages that return status information or report errors that are not severe. The
Database Engine does not raise system errors with severities of 0 through 9.
• 10: Informational messages that return status information or report errors that are not severe. For
compatibility reasons, the Database Engine converts severity 10 to severity 0 before returning the error
information to the calling application.
• 11-16: Indicate errors that can be corrected by the user.
1. 11: Indicates that the given object or entity does not exist.
2. 12: A special severity for queries that do not use locking because of special query hints. In some cases,
read operations performed by these statements could result in inconsistent data since locks are not
taken to guarantee consistency.
3. 13: Indicates transaction deadlock errors.
4. 14: Indicates security-related errors, such as permission denied.
5. 15: Indicates syntax errors in the Transact-SQL command.
6. 16: Indicates general errors that can be corrected by the user.
• 17-19: Indicate software errors that cannot be corrected by the user. Inform your system administrator of
the problem.
1. 17: Indicates that the statement caused SQL Server to run out of resources (such as memory, locks,
or disk space for the database) or to exceed some limit set by the system administrator.
2. 18: Indicates a problem in the Database Engine software, but the statement completes execution,
and the connection to the instance of the Database Engine is maintained. The system administrator
should be informed every time a message with a severity level of 18 occurs.
3. 19: Indicates that a non-configurable Database Engine limit has been exceeded and the current batch
process has been terminated. Error messages with a severity level of 19 or higher stop the execution of
the current batch. Severity level 19 errors are rare and must be corrected by the system administrator
or your primary support provider. Contact your system administrator when a message with a severity
level 19 is raised. Error messages with a severity level from 19 through 25 are written to the error log.
• 20-24 Indicate system problems and are fatal errors, which means that the Database Engine task that is
executing a statement or batch is no longer running. The task records information about what occurred
and then terminates. In most cases, the application connection to the instance of the Database Engine may
also terminate. If this happens, depending on the problem, the application might not be able to reconnect.
Error messages in this range can affect all of the processes accessing data in the same database and may
indicate that a database or object is damaged. Error messages with a severity level from 19 through 24 are
written to the error log.
1. 20: Indicates that a statement has encountered a problem. Because the problem has affected only the
current task, it is unlikely that the database itself has been damaged.
2. 21: Indicates that a problem has been encountered that affects all tasks in the current database, but
it is unlikely that the database itself has been damaged.
3. 22: Indicates that the table or index specified in the message has been damaged by a software or
hardware problem. Severity level 22 errors occur rarely. If one occurs, run DBCC CHECKDB to
determine whether other objects in the database are also damaged. The problem might be in the
2.4. INSTALLATION 35
buffer cache only and not on the disk itself. If so, restarting the instance of the Database Engine
corrects the problem. To continue working, you must reconnect to the instance of the Database
Engine; otherwise, use DBCC to repair the problem. In some cases, you may have to restore the
database. If restarting the instance of the Database Engine does not correct the problem, then the
problem is on the disk. Sometimes destroying the object specified in the error message can solve the
problem. For example, if the message reports that the instance of the Database Engine has found a
row with a length of 0 in a nonclustered index, delete the index and rebuild it.
4. 23: Indicates that the integrity of the entire database is in question because of a hardware or software
problem. Severity level 23 errors occur rarely. If one occurs, run DBCC CHECKDB to determine
the extent of the damage. The problem might be in the cache only and not on the disk itself. If so,
restarting the instance of the Database Engine corrects the problem. To continue working, you must
reconnect to the instance of the Database Engine; otherwise, use DBCC to repair the problem. In
some cases, you may have to restore the database.
5. 24: Indicates a media failure. The system administrator may have to restore the database. You may
also have to call your hardware vendor.
2.4 Installation
1. Download SQL Server official link.
36 CHAPTER 2. SQL SERVER & SQL SERVER MANAGEMENT STUDIO
2. Open the software by double-clicking on it. Select Basic from the provided options.
3. Select Accept.
2.4. INSTALLATION 37
4. Press Install.
5. Wait for the installation to Complete.
38 CHAPTER 2. SQL SERVER & SQL SERVER MANAGEMENT STUDIO
6. Press the Customization Button from options.
7. Press Next till reach you reach “Feature Selection”
2.4. INSTALLATION 39
8. Check Database Engine Services
9. Now Press Next till reach you reach “Database Engine Configuration”, Click “Add Current User”, and
Press Next.
40 CHAPTER 2. SQL SERVER & SQL SERVER MANAGEMENT STUDIO
10. Press Install. Close the Window After Completion.
11. Now Click on ”Install SSMS”.
2.4. INSTALLATION 41
12. Download setup file.
13. Open the software by double-clicking on it. Press Install.
42 CHAPTER 2. SQL SERVER & SQL SERVER MANAGEMENT STUDIO
14. Press Close after completion.
2.5 Create New Login
1. Security - Login - New Login
2.5. CREATE NEW LOGIN 43
2. Provide Unique Name - Select SQL Authentication - Check only Enforce a password policy
3. From Select a Page go to Server Roles - Check public and sysadmin
44 CHAPTER 2. SQL SERVER & SQL SERVER MANAGEMENT STUDIO
4. From Select a Page go to User Mapping - Select Database for the New Login
Chapter 3
Transact-SQL Statements (Basic)
3.1 Load Data-set on SQL Server Management Studio
1. Open SSMS from the start menu
45
46 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
2. Connect to Server.
3. Right-click on Databases from Object Explorer, Click on new Database
3.1. LOAD DATA-SET ON SQL SERVER MANAGEMENT STUDIO 47
4. Type name & Press OK
5. Now Right click on the newly named database, Select Tasks then Import Flat File
48 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
6. Press Next, and provide the file path in the first textbox then press next.
7. In modify columns tab change nvarchar(50) to varchar(max) for each column, Press Next and Finish
3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 49
8. Wait for Results to compile, press close
3.2 DML (Data Manipulation Language) Statements
1. Right Click on the newly created Database and select New Query
50 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
2. Display Whole Table
3. Display Few Columns
3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 51
4. Display Distinct Values in one column
5. Display Count of Distinct Values for a column
52 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
6. Display rows having Same Value (String)
7. Display rows having the Same Value (Number)
3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 53
8. Display rows having Greater Value
9. Display rows having Less Value
54 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
10. Display rows having Greater/Equal Value
11. Display rows having Less/Equal Value
3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 55
12. Display rows having not same Value
13. Display rows having Range Values
56 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
14. Display rows having the same character at Start in Value
15. Display rows having the same character at End in Value
3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 57
16. Display rows having the same character at Any Position in Value
17. Display rows having the same character at the Second Position in Value
58 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
18. Display rows having the same character at Start with at least 6 characters in Value
19. Display rows having different characters at Start in Value
3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 59
20. Display rows having the same character range at Start in Value
21. Display rows having the same multiple characters at Start in Value
60 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
22. Display rows having the same character at the Start and end in Value
23. Display rows having Value in specified Strings
3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 61
24. Display rows having Multiple conditions True
25. Display rows having At-least one condition True
62 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
26. Display rows having No Condition True
27. Display rows having Null Value
3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 63
28. Display rows having No Null Value
29. Display Sorted rows using one column
64 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
30. Display Sorted rows using one column (Decreasing)
31. Display Sorted rows using Multiple columns
3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 65
32. Display Top n Values
33. Display Top n Percent Values
66 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
34. Display Top n Values (using Where)
35. Display Minimum Values of a Column
3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 67
36. Display Maximum Values of a Column
37. Display Average of a Column
68 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
38. Display Sum of a Column
39. Display same column with a new name
3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 69
40. Display Column Values in groups
41. Display rows having specified values
70 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
42. Create Tags for each group values
43. Insert Columns in New Tables
3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 71
44. Insert values in the row
45. Update Values
72 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
46. Update Values (Multiple)
47. Delete Values
3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 73
48. Display rows on one table by using a second table (exists)
49. Display rows on one table by using a second table (Any)
74 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
50. Display rows on one table by using a second table (ALL)
51. Join Two Tables using Inner Join
3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 75
52. Join Two Tables using Left Join
53. Join Two Tables using Right Join
76 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
54. Join Two Tables using Outer Join
55. Take Union of Two Tables
3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 77
56. Take Intersection of Two Tables
57. Replace Null Values (Temporary)
78 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
3.3 Data Definition Language (DDL)
3.3.1 Procedure/Variables for Existing Database
1. Create a Procedure
2. Execute Procedure
3.3. DATA DEFINITION LANGUAGE (DDL) 79
3. Create a variable and use it in Query
3.3.2 Database
1. Create Database
80 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
2. For Backup Permission in C Drive, Select SQL Server 2019 Configuration Manager
3. Open SQL Server and select local System in Build-in Account
3.3. DATA DEFINITION LANGUAGE (DDL) 81
4. Backup Database
5. Backup Database (Only Changes)
82 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
6. Delete Database
7. Restore Database
3.3. DATA DEFINITION LANGUAGE (DDL) 83
3.3.3 Table
1. Create Table
2. Delete Table
84 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
3. Truncate Table
4. Add new column to a Table
3.3. DATA DEFINITION LANGUAGE (DDL) 85
3.3.4 Column
1. Change column properties
2. Delete column
86 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
3. Change Property of a column (null)
4. Change Property of a column (not null)
3.3. DATA DEFINITION LANGUAGE (DDL) 87
5. Change Property of a column (Unique)
6. Change Property of a column (primary)
88 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
7. Change Property of a column (Check)
8. Change Property of a column (Default)
3.3. DATA DEFINITION LANGUAGE (DDL) 89
9. Run Serial in one column
90 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
Chapter 4
School Management System
4.1 ER-Diagram
91
92 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM
4.2 Database Development
1. Create Database named School Management System
2. Create Table named Attendance
• Attendance ID (PK, int, not null, auto-increment)
• Class (varchar(20))
• Session (varchar(10))
• Section (varchar(10))
• Subject Code (FK, varchar(20))
• Staff ID (varchar(15))
• Attendance Date (datetime)
• Admission Number (FK, varchar(15))
• Status (varchar(10))
4.2. DATABASE DEVELOPMENT 93
3. Create Table named Book
• Accession Number (PK, varchar(30), not null)
• Book Title (varchar(30))
• Author (varchar(30))
• Joint Authors (varchar(30))
• Subject (varchar(30))
• Department (varchar(30))
• Barcode (varchar(70))
• ISBN (varchar(30))
• Volume (varchar(30))
• Edition (varchar(30))
• Publisher (varchar(30))
• Place of Publisher (varchar(30))
• CD (varchar(10))
• Publishing Year (int)
• Reference (varchar(10))
• Almira Position (varchar(30))
• Price (int)
• Supplier Name (varchar(30))
• Bill Date (datetime)
• Remarks (varchar(max))
94 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM
4. Create Table named Book Issue Staff
• Transaction ID (PK, varchar(15), not null)
• Issue Date (datetime)
• Due Date (datetime)
• Accession No (varchar(30))
• Staff ID (varchar(15))
• Status (varchar(30))
5. Create Table named Book Return Student
• Return ID (PK, varchar(15), not null)
• Transaction ID (varchar(15))
• Return Date (datetime)
4.2. DATABASE DEVELOPMENT 95
• Fine (int)
6. Create Table named Bus Holders
• Admission Number (varchar(15))
• Source Location (varchar(250))
• Starting Date (date)
7. Create Table named Class
• ID (PK, int, not null)
• Class Name (varchar(20))
• Section (varchar(20))
96 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM
8. Create Table named Course Fee
• ID (PK, int, not null)
• Class ID (int)
• Fee ID (int)
• Fee (float)
• Month (varchar(30))
9. Create Table named Department
• ID (PK, int, not null)
• Department Name (varchar(250), not null)
4.2. DATABASE DEVELOPMENT 97
10. Create Table named Employee
• Staff ID (PK, varchar(50), not null)
• Staff Name (varchar(30))
• Father Name (varchar(30))
• Mother Name (varchar(30))
• Date of Birth (date)
• Permanent Address (varchar(100))
• Temporary Address (varchar(100))
• Phone Number (varchar(11))
• Mobile Number (varchar(11))
• Date of Joining (date)
• Qualification (varchar(70))
• Years of Experience (float)
• Designation (varchar(100))
• Email (varchar(30))
• Picture (image)
• Status (varchar(15))
• Basic Salary (int)
• Department (varchar(100))
• Gender (varchar(10))
98 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM
11. Create Table named Event
• Event ID (PK, int, not null)
• Event Name (varchar(150))
• Starting Date and Time (datetime)
• Ending Date and Time (datetime)
• Managed By (varchar(250))
• Activities (varchar(max))
12. Create Table named Examination
• ID (PK, int, not null)
• Examination Name (varchar(30))
• Examination Type (varchar(30))
4.2. DATABASE DEVELOPMENT 99
13. Create Table named Fee
• ID (PK, int, not null)
• Fee Name (varchar(50))
14. Create Table named Grades
• Grade ID (PK, int, not null)
• Grade (varchar(50))
• Score From (float)
• Score To (float)
• Remark (varchar(max))
• Grade Points (float)
100 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM
15. Create Table named Hostel Fee Payment
• Hostel Fee Payment ID (PK, varchar(15), not null)
• Admission Number (varchar(15))
• Total Paid (int)
• Mode of Payment (varchar(50))
• Payment Mode details (varchar(200))
• Fine (int)
• Due Fees (int)
• Date and Time of Payment (datetime)
• Hostel Fees (int)
16. Create Table named Hostel Information
4.2. DATABASE DEVELOPMENT 101
• ID (PK, int, not null)
• Hostel Name (varchar(150), not null)
• Hostel Address (varchar(150), not null)
• Managed By (varchar(100))
• Hostel Phone Number (varchar(11), not null)
• Hostel Mobile Number (varchar(11))
• Hostel Fees (int)
17. Create Table named Marks Entry
• Marks Entry ID (PK, int, not null)
• Admission Number (varchar(15))
• Student School (varchar(250))
• Session (varchar(100))
• Student Class (varchar(150))
• Student Section (varchar(100))
• Entry Date (datetime)
• Result (varchar(20))
102 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM
18. Create Table named Scholarship
• Scholarship ID (PK, int, not null)
• Scholarship Name (varchar(30))
• Description (varchar(max))
• Amount (int)
19. Create Table named School
• School ID (PK, int, not null)
• School Name (varchar(250))
• Address (varchar(250))
• Contact Number (varchar(11))
• Email (varchar(30))
4.2. DATABASE DEVELOPMENT 103
• Website (varchar(60))
20. Create Table named Student
• Admission Number (PK, varchar(15), not null)
• Enrollment Number (varchar(15))
• Student Name (varchar(100))
• Father Name (varchar(100))
• Mother Name (varchar(100))
• Father Contact Number (varchar(11))
• Permanent Address (varchar(250))
• Temporary Address (varchar(250))
• Student Contact Number (varchar(11))
• Email ID (varchar(60))
• Date of Birth (date)
• Gender (varchar(10))
• Admission Date (date)
• Session (varchar(15))
• Caste (varchar(15))
• Religion (varchar(15))
• Photo (image)
• Status(varchar(15))
• Nationality (varchar(50))
• Class (varchar(20))
• Section (varchar(30))
• School ID (int)
104 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM
21. Create Table named Subject
• Subject Code (PK, varchar(20), not null)
• Subject Name (varchar(250))
• Class Name (varchar(20))
22. Create Table named Supplier
• ID (PK, varchar(15), not null)
• Supplier Name (varchar(30))
• Address (varchar(200))
• Contact No (varchar(15))
4.2. DATABASE DEVELOPMENT 105
• Email ID (varchar(50))
23. Create Table named Transportation
• Route ID (PK, int, not null)
• Source Location (varchar(250))
• Bus Charges (int)
24. Add Foreign Key Constraints to following Columns
• Attendance (Subject Code) with Subject (Subject Code)
• Attendance (Admission Number) with Student (Admission Number)
• Book Issue Staff (Accession Number) with Book (Accession Number)
• Book Issue Staff (Staff ID) with Employee (Staff ID)
• Bus Holder (Admission Number) with Student (Admission Number)
106 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM
• Course Fee (Class ID) with Class (ID)
• Course Fee (Fee ID) with Fee (ID)
• Hostel Fee Payment (Admission Number) with Student (Admission Number)
• Student (School ID) with School (school ID)
4.3 User Interface
1. Connect Database to your Visual Studio
4.3. USER INTERFACE 107
2. Login Page
using System;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace SchoolManagementSystem
{
public partial class Login : Form
{
private string role;
private string connectString = "Data Source=(LocalDB)MSSQLLocalDB;AttachDb" +
"Filename=|DataDirectory|SchoolManagementSystem.mdf;Integrated Securit" +
"y=True";
public Login() => InitializeComponent();
public string Role { get => role; set => role = value; }
public string setrole()
{
if (radioButtonAdmin.Checked == true)
Role = "admin";
else if (radioButtonParent.Checked == true)
Role = "parent";
else if (radioButtonStudent.Checked == true)
Role = "student";
else if (radioButtonTeacher.Checked == true)
Role = "teacher";
else
Role = " ";
return Role;
}
private void ButtonLogin_Click(object sender, EventArgs e)
{
SqlConnection sqlcon = new SqlConnection();
sqlcon.ConnectionString = connectString;
sqlcon.Open();
108 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM
string username = textBoxUsername.Text;
string password = textBoxPassword.Text;
string role = setrole();
string query = "select userName, passWord, role from login where userNam" +
"e='" + textBoxUsername.Text + "'and passWord='" + textBoxPassword.Text
+ "'and role='" + role + "'";
SqlCommand cmd = new SqlCommand(query, sqlcon);
SqlDataAdapter da = new SqlDataAdapter(cmd);
if (da != null)
{
if (role == "admin")
{
Administrator adminForm = new Administrator();
adminForm.Visible = true;
this.Hide();
}
else if (role == "parent")
{
Parent parentForm = new Parent();
parentForm.Visible = true;
this.Hide();
}
else if (role == "teacher")
{
Teacher teacherForm = new Teacher(username);
teacherForm.Visible = true;
this.Hide();
}
else if (role == "student")
{
Students studentForm = new Students(username);
studentForm.Visible = true;
this.Hide();
}
}
else
{
MessageBox.Show("Invalid Login please check username/password/role");
}
}
}
}
4.3. USER INTERFACE 109
3. Admin Page
• View Employee or Student Record using their IDs
• Add or Delete Login Credentials
• Add or Delete Employee Information
110 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM
• Add or Delete Student Information
• View, Add and Delete School Information
• Add, View and Delete Hostel Information
using System;
using System.Data;
4.3. USER INTERFACE 111
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace SchoolManagementSystem
{
public partial class Administrator : Form
{
public string connection = "Data Source=(LocalDB)MSSQLLocalDB;AttachDbFil" +
"ename=|DataDirectory|SchoolManagementSystem.mdf;Integrated Security=True";
public string query;
public string imgLocation;
SqlConnection sqlcon = new SqlConnection();
SqlDataReader reader;
byte[] images = null;
public void opensql()
{
sqlcon.ConnectionString = connection;
sqlcon.Open();
}
public void queryexecute()
{
SqlCommand cmd = new SqlCommand(query, sqlcon);
cmd.Connection = sqlcon;
cmd.CommandType = CommandType.Text;
int a = cmd.ExecuteNonQuery();
if (a != -1)
{
MessageBox.Show("Successful");
}
else
{
MessageBox.Show("Error");
}
}
public void queryexecutearray()
{
SqlCommand cmd = new SqlCommand(query, sqlcon);
reader = cmd.ExecuteReader();
reader.Read();
}
public String addpicture()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
imgLocation = openFileDialog.FileName.ToString();
return imgLocation;
}
return null;
}
public void addpictureinrecord()
{
FileStream stream = new FileStream(imgLocation, FileMode.Open,
FileAccess.Read);
BinaryReader brs = new BinaryReader(stream);
images = brs.ReadBytes((int)stream.Length);
}
public Administrator()
112 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM
{
InitializeComponent();
}
//Add New Login Details
private void button2_Click(object sender, EventArgs e)
{
opensql();
query = "insert into login values ('" + textBox2.Text + "','" +
textBox3.Text + "','" + textBox4.Text + "')";
queryexecute();
sqlcon.Close();
}
//Remove Old Login Detail
private void button3_Click_1(object sender, EventArgs e)
{
opensql();
query = "delete from login where username = '" +
textBox2.Text + "'";
queryexecute();
sqlcon.Close();
}
//Update Login Details
private void button17_Click(object sender, EventArgs e)
{
opensql();
if (String.IsNullOrEmpty(textBox2.Text))
{
MessageBox.Show("Enter Username");
}
else
{
if (String.IsNullOrEmpty(textBox4.Text))
{
query = "update login set passWord = '" +
textBox3.Text + "' where userName = '" + textBox2.Text + "'";
queryexecute();
}
else if (String.IsNullOrEmpty(textBox3.Text))
{
query = "update login set role = '" +
textBox4.Text + "' where userName = '" + textBox2.Text + "'";
queryexecute();
}
else
{
query = "update login set role = '" +
textBox4.Text + "', passWord = '" + textBox3.Text + "' where " +
"userName = '" + textBox2.Text + "'";
queryexecute();
}
}
sqlcon.Close();
}
//View Login Details
private void button16_Click(object sender, EventArgs e)
{
opensql();
query = "select * from login where userName = '" +
textBox2.Text + "'";
queryexecutearray();
textBox3.Text = (String)reader[1];
4.3. USER INTERFACE 113
textBox4.Text = (String)reader[2];
sqlcon.Close();
}
//View Employee or Student Information
private void button1_Click(object sender, EventArgs e)
{
opensql();
if (radioButton1.Checked == true)
query = "select *, convert(varchar(max), dateOfJoining), convert(var" +
"char(max), dateOfBirth), convert(varchar(max), yearsOfExperienc" +
"e), convert(varchar(max), basicSalary) from employee where staf" +
"fID = '" + textBox1.Text + "'";
else if (radioButton2.Checked == true)
query = "select *, convert(varchar(max),dateOfBirth), convert(varcha" +
"r(max),admissionDate), convert(varchar(max),schoolID) from stud" +
"ent where enrollmentNumber = '" + textBox1.Text + "'";
else
MessageBox.Show("Select one of the above option");
queryexecutearray();
if (radioButton1.Checked == true)
{
label2.Text = "Staff ID: " + "n" + "Date of Joining: "+"n" + "Empl" +
"oyee Name: " + "n" + "Father's Name: " + "n" + "Mother's Na" +
"me: " + "n" + "Date of Birth: " + "n" + "Gender: " + "n" +
"Parmenant Address: " + "n" + "Temporary Address: " + "n" +
"Personal Number: " + "n" + "Professional Number: " + "n" + "" +
"Qualification: " + "n" + "Expirence: " + "n" + "Designation: " +
"" + "n" + "Email: " + "n" + "Status: " + "n" + "Salary: " +
"n" + "Deparment: ";
label3.Text = (string)reader[0] + "n" + (string)reader[19] + "n" +
(string)reader[1] + "n" + (string)reader[2] + "n" +
(string)reader[3] + "n" + (string)reader[20] + "n" +
(string)reader[18] + "n" + (string)reader[5] + "n" +
(string)reader[6] + "n" + (string)reader[8] + "n" +
(string)reader[7] + "n" + (string)reader[10] + "n" +
(string)reader[20] + "n" + (string)reader[12] + "n" +
(string)reader[13] + "n" + (string)reader[15] + "n" +
(string)reader[21] + "n" + (string)reader[17];
byte[] photo = (byte[])reader[14];
if (photo != null)
{
MemoryStream ms = new MemoryStream(photo);
pictureBox2.Image = Image.FromStream(ms);
}
}
else if (radioButton2.Checked == true)
{
label2.Text = "Admission Number: " + "n" + "Enrollment Number: " +
"n" + "Student Name: " + "n" + "Father's Name: " + "n" + "Mot" +
"her's Name: " + "n" + "Date of Birth: " + "n" + "Gender: " +
"n" + "Parmenant Address: " + "n" + "Temporary Address: " +
"n" + "Personal Number: " + "n" + "Father's Number: " + "n" +
"Email ID: " + "n" + "Admission Date: " + "n" + "Session: " +
"n" + "Caste: " + "n" + "Religion: " + "n" + "Status: " + "n"
+ "Nationality: " + "n" + "Class: " + "n" + "Section: " + "n"
+ "School ID: ";
label3.Text = (string)reader[0] + "n" + (string)reader[1] + "n"
+ (string)reader[2] + "n" + (string)reader[3] + "n" +
(string)reader[4] + "n" + (string)reader[22] + "n" +
(string)reader[11] + "n" + (string)reader[6] + "n" +
114 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM
(string)reader[7] + "n" + (string)reader[8] + "n" +
(string)reader[5] + "n" + (string)reader[9] + "n" +
(string)reader[23] + "n" + (string)reader[13] + "n" +
(string)reader[14] + "n" + (string)reader[15] + "n" +
(string)reader[17] + "n" + (string)reader[18] + "n" +
(string)reader[19] + "n" + (string)reader[20] + "n" +
(string)reader[24];
byte[] photo = (byte[])reader[16];
if (photo != null)
{
MemoryStream ms = new MemoryStream(photo);
pictureBox2.Image = Image.FromStream(ms);
}
}
label23.Text = "Photo";
sqlcon.Close();
}
//Add Picture (Employee)
private void button4_Click_1(object sender, EventArgs e)
{
pictureBox1.ImageLocation = addpicture();
}
//Add Picture (Student)
private void button9_Click(object sender, EventArgs e)
{
pictureBox3.ImageLocation = addpicture();
}
//Add Employee Record
private void button5_Click(object sender, EventArgs e)
{
addpictureinrecord();
opensql();
query = "insert into employee values ('" + textBox18.Text + "','"
+ textBox17.Text + "','" + textBox16.Text + "','" + textBox15.Text +
"','" + textBox14.Text + "','" + textBox13.Text + "','" +
textBox12.Text + "','" + textBox11.Text + "','" + textBox10.Text +
"','" + textBox9.Text + "','" + textBox8.Text + "','" + textBox6.Text
+ "','" + textBox7.Text + "','" + textBox19.Text + "', @images,'" +
textBox20.Text + "','" + textBox21.Text + "','" + textBox22.Text +
"','" + textBox23.Text + "')";
queryexecute();
sqlcon.Close();
}
//Delete Employee Record
private void button6_Click(object sender, EventArgs e)
{
opensql();
query = "delete from employee where username = '" +
textBox18.Text + "'";
queryexecute();
sqlcon.Close();
}
//Add Student Information
private void button8_Click(object sender, EventArgs e)
{
addpictureinrecord();
opensql();
query = "insert into student (admissionNumber, enrollmentNumber, " +
"studentName, fatherName, motherName, fatherContactNumber, " +
"permanentAddress, TemporaryAddress, studentContactNumber, emailID, " +
4.3. USER INTERFACE 115
"dateOfBirth, gender, admissionDate, session, caste, religion, status, " +
"nationality, class, section, schoolID, photo) select '" +
textBox24.Text + "','" + textBox25.Text + "','" + textBox26.Text +
"','" + textBox27.Text + "','" + textBox28.Text + "','" +
textBox29.Text + "','" + textBox30.Text + "', '" + textBox31.Text +
"','" + textBox32.Text + "','" + textBox33.Text + "',convert(date,'"
+ textBox34.Text + "'),'" + textBox35.Text + "',convert(date,'" +
textBox36.Text + "'), '" + textBox37.Text + "', '" + textBox38.Text +
"', '" + textBox39.Text + "', '" + textBox40.Text + "', '" +
textBox41.Text + "', '" + textBox42.Text + "', '" + textBox43.Text +
"', '" + textBox44.Text + "', @images";
queryexecute();
sqlcon.Close();
}
//Delete Student Information
private void button7_Click(object sender, EventArgs e)
{
opensql();
query = "delete from student where admissionNumber = '" +
textBox24.Text + "'";
queryexecute();
sqlcon.Close();
}
//View School Details
private void button11_Click(object sender, EventArgs e)
{
opensql();
query = "select * from school where schoolID = '" +
textBox45.Text + "'";
queryexecutearray();
textBox46.Text = (String)reader[1];
textBox47.Text = (String)reader[2];
textBox48.Text = (String)reader[3];
textBox49.Text = (String)reader[4];
textBox50.Text = (String)reader[5];
sqlcon.Close();
}
//Add School Details
private void button10_Click(object sender, EventArgs e)
{
opensql();
query = "insert into school values ('" + textBox45.Text + "','"
+ textBox46.Text + "','" + textBox47.Text + "','" + textBox48.Text
+ "','" + textBox49.Text + "','" + textBox50.Text + "')";
queryexecute();
sqlcon.Close();
}
//Remove School Details
private void button12_Click(object sender, EventArgs e)
{
opensql();
query = "delete from school where schoolID = '" +
textBox45.Text + "'";
queryexecute();
sqlcon.Close();
}
//View Hostel Details
private void button14_Click(object sender, EventArgs e)
{
opensql();
query = "select *, convert(varchar(max), hostelFees) from " +
116 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM
"hostelInformation where ID = '" + textBox56.Text + "'";
queryexecutearray();
textBox55.Text = (String)reader[1];
textBox54.Text = (String)reader[2];
textBox51.Text = (String)reader[3];
textBox57.Text = (String)reader[4];
textBox53.Text = (String)reader[5];
textBox52.Text = (String)reader[7];
sqlcon.Close();
}
//Add Hostel Detail
private void button15_Click(object sender, EventArgs e)
{
opensql();
query = "insert into hostelInformation values ('" + textBox56.Text
+ "','" + textBox55.Text + "','" + textBox54.Text + "','" +
textBox51.Text + "','" + textBox57.Text + "','" + textBox53.Text + "'," +
"'" + textBox52.Text + "')";
queryexecute();
sqlcon.Close();
}
//Delete Hostel Details
private void button13_Click(object sender, EventArgs e)
{
opensql();
query = "delete from hostelInformation where ID = '" +
textBox56.Text + "'";
queryexecute();
sqlcon.Close();
}
}
}
Chapter 5
Transact-SQL Statements
(Intermediate)
5.1 Joins
1. Display Customers Details like Title, Full Name (First Name, Middle Name, Last Name, Suffix), Full
Address (AddressLine1, AddressLine2, City, StateProvince, CountryRegion), Postal Code, and Phone No
117
118 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE)
2. Display Customer ID, Full Name, Product Name, Color and Unit Price
3. Display Product Name, Standard Cost, List Cost, Total Orders and Total Profit
5.1. JOINS 119
4. Display Combined List of First Name and Last Name with at least 3 characters
5. Display Product Name, Total Orders and State/Province from which Orders were Placed
120 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE)
6. Display Product Name, Category Name and Model Name
7. Display Product Name, Category Name, Model Name and Culture
5.1. JOINS 121
8. Display Parent Category and Child Category
9. Display Product Name and its Description
122 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE)
10. Display Company Name an Email Address where Freight rate is more than 1000
11. Calculate the Percentage of Subtotal and Tax amount
5.2. VARIABLES AND PROCEDURES 123
12. Display Customer ID, Full Name (Title, First Name, Middle Name, Last Name, Suffix), Company Name,
Phone, Address Type, Full Address (AddressLine1, AddressLine2, City, State, Country, Postal Code),
Subtotal, Tax Amount, Freight Rate, Total Cost
5.2 Variables and Procedures
1. Declare a variable with datatype int
124 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE)
2. Declare a variable with datatype varchar
3. Declare and Assign a value to a variable
5.2. VARIABLES AND PROCEDURES 125
4. Declare, Assign and Display the value of a variable
5. Using Variables Display Products in given Price Range
126 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE)
6. Using variables Display Count of Specific Color
7. Create Procedure having a variable for colour and Display its count
5.2. VARIABLES AND PROCEDURES 127
8. Create a Procedure that displays records for a given postal code
9. Create a Procedure that displays records for a given total profit
128 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE)
10. Create a Procedure that displays the record for a given Order Quantity or Product ID
11. Create a Procedure that displays a message of the total amount for a given Sales ID
5.3. SUB-QUERIES AND VIEWS 129
5.3 Sub-queries and Views
1. Display Specific Customer Details using sub-query
2. Display Product having maximum sales using sub-query
130 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE)
3. Display Customers from Canada using Sub-Query
4. Display Customers who paid more than 200 in Freight rate using Sub-Query
5.3. SUB-QUERIES AND VIEWS 131
5. Create View to display Customer First Name and Phone Number
6. Create View and Procedure to display Customer First Name and Phone Number where the First name is
Dominic
132 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE)
7. Create View to display Product Sales report where the minimum sale is 30
8. Create View and insert data
5.3. SUB-QUERIES AND VIEWS 133
9. Create View to update values
10. Alter View, add checkpoint and try to update values
Note: You can only insert or delete from a single table. If you make any changes to the base tables you can use
the sp refreshview procedure to recompile the view.
134 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE)
5.4 Program Flow Statements
1. Return
2. Throw (Error Code, Message, State)
5.4. PROGRAM FLOW STATEMENTS 135
3. Try Catch
4. Waitfor (time)
136 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE)
5. Waitfor (delay)
6. While
5.4. PROGRAM FLOW STATEMENTS 137
7. Begin End
8. Break
138 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE)
9. Continue
10. If else
5.5. TRANSACTIONS 139
11. Goto
5.5 Transactions
1. Create a Transaction to delete the customer
140 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE)
2. Create a Transaction to insert the product details
3. Create a Transaction to update the product detail
5.5. TRANSACTIONS 141
4. Create a Transaction to delete the customer and commit it
5. Create a Transaction to insert the product details and rollback it
142 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE)
6. Create a Transaction to delete the customer and add save points to which we can rollback
Note: To check the oldest active transaction use DBCC OPENTRAN
5.6 Triggers
1. Create insert Trigger for List Price
5.6. TRIGGERS 143
2. Create update Trigger for Modified Date
3. Create delete Trigger for Product ID
144 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE)
4. Create create Trigger for database
5. Create alter Trigger for database
5.6. TRIGGERS 145
6. Create drop Trigger for database
Note: Trigger is a stored routine. it is a set of SQL statements used for protecting the integrity of data. But
constraint is used to define rules to allow or restrict what values can be stored in columns. The purpose of
inducing constraints is to enforce the integrity of the database. it restricts the insertion of data in a table.
The trigger can be on update/delete statements also, but constraints are related to providing restrictions while
inserting the data.
All insert, update, and delete triggers can be found in respective trigger folders in Table details, whereas all
create, drop, and alter triggers are stored in database triggers which can be found in the programmability folder
of the respective database.
146 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE)
Chapter 6
Malicious
6.1 Queries
1. Display all products excluding the top 10 products
147
148 CHAPTER 6. MALICIOUS
2. Display 20 products excluding the top 10 products
3. Display top 12 products including similar values
6.1. QUERIES 149
4. By using self-join display Category and sub-category
5. Display list using cross join
150 CHAPTER 6. MALICIOUS
6. Display Products using the correlated query
7. Create Order Detail Summary using cube
6.1. QUERIES 151
8. Create Order Detail Summary using rollup 1
9. Display newly inserted record on the screen
1Note: The difference between cube and rollup is that cube generates all possible combinations for the given attributes whereas
rollup only generates hierarchical combinations
152 CHAPTER 6. MALICIOUS
10. insert multiple records at once
11. Copy only table structure
6.1. QUERIES 153
12. Copy only the top 10 percent sold products to the new table
13. Show count of customers in the state vs country
154 CHAPTER 6. MALICIOUS
14. Create Schema for your database
15. Create a new table in the schema
6.1. QUERIES 155
16. Add a new computed column to your table
17. Create a local temporary table
156 CHAPTER 6. MALICIOUS
18. Create a global temporary table
19. Create a Synonym for the table
6.2. CREATE SETUP FILE 157
20. Set a column to generate Globally unique identifier
21. Change the order of forms in Visual Studio
(a) Double Click file named Programs.cs
(b) Change form1 to your desired form class in ”Application.Run(new form1());”
6.2 Create Setup File
(a) Go to Extensions, select Manage Extensions, search setup and download Microsoft Visual Studio
Installer Project
158 CHAPTER 6. MALICIOUS
(b) Close Visual Studio, Click on Modify and wait for the setup to complete
(c) Reopen your Visual Studio Project, Right Click on Solution and select Add New Project
6.2. CREATE SETUP FILE 159
(d) Select Setup Project and name it.
(e) Right Click on Application Folder, and Select Project Output
160 CHAPTER 6. MALICIOUS
(f) Click OK
(g) Right Click on Application Folder and Add your database files
6.2. CREATE SETUP FILE 161
(h) Select User’s Desktop, Right click on the window, select Application folder and primary output file
and rename it
(i) Select User’s Program Menu, Create a new folder, Create Shortcut and rename it
162 CHAPTER 6. MALICIOUS
(j) In Solution Explorer right click on the setup file, select properties, click on Prerequisites, select SQL
Server 2019, and Click OK
(k) Select database from Application Folder and change Property Permanent to True
6.2. CREATE SETUP FILE 163
(l) Click on Properties, select publish, click on prerequisite, select SQL Server 2019
(m) Click on the option and provide details and press OK, Now click on Publish and your setup is complete
164 CHAPTER 6. MALICIOUS
Appendix A
Lab Details
Lab No Chapter
01 Visual Studio
02 SQL Server & SQL Server Management Studio
03
Transact-SQL Statements (Basic)
04
05
06
School Management System
07
08
Transact-SQL Statements (Intermediate)
09
10
11
12
13
14
Malicious
15
16 Students’ Questions
165

More Related Content

Similar to DBMS_Lab_Manual_&_Solution

programación en prolog
programación en prologprogramación en prolog
programación en prologAlex Pin
 
Ibm tivoli intelligent think dynamic orchestrator pre proof of-concept cookbo...
Ibm tivoli intelligent think dynamic orchestrator pre proof of-concept cookbo...Ibm tivoli intelligent think dynamic orchestrator pre proof of-concept cookbo...
Ibm tivoli intelligent think dynamic orchestrator pre proof of-concept cookbo...Banking at Ho Chi Minh city
 
BOOK - IBM Implementing ibm system directory 6.1
BOOK - IBM Implementing ibm system directory 6.1BOOK - IBM Implementing ibm system directory 6.1
BOOK - IBM Implementing ibm system directory 6.1Satya Harish
 
bkremer-report-final
bkremer-report-finalbkremer-report-final
bkremer-report-finalBen Kremer
 
OpenScape Contact Center Enterprise V10 Manager Administration Guide Administ...
OpenScape Contact Center Enterprise V10 Manager Administration Guide Administ...OpenScape Contact Center Enterprise V10 Manager Administration Guide Administ...
OpenScape Contact Center Enterprise V10 Manager Administration Guide Administ...EnriqueJoseCaleroGal
 
Modifying infor erp_syte_line_5140
Modifying infor erp_syte_line_5140Modifying infor erp_syte_line_5140
Modifying infor erp_syte_line_5140rajesh_rolta
 
Deployment guide series ibm tivoli usage and accounting manager v7.1 sg247569
Deployment guide series ibm tivoli usage and accounting manager v7.1 sg247569Deployment guide series ibm tivoli usage and accounting manager v7.1 sg247569
Deployment guide series ibm tivoli usage and accounting manager v7.1 sg247569Banking at Ho Chi Minh city
 
Certification guide series ibm tivoli provisioning manager v5.1 sg247262
Certification guide series ibm tivoli provisioning manager v5.1 sg247262Certification guide series ibm tivoli provisioning manager v5.1 sg247262
Certification guide series ibm tivoli provisioning manager v5.1 sg247262Banking at Ho Chi Minh city
 
Solution deployment guide for ibm tivoli composite application manager for we...
Solution deployment guide for ibm tivoli composite application manager for we...Solution deployment guide for ibm tivoli composite application manager for we...
Solution deployment guide for ibm tivoli composite application manager for we...Banking at Ho Chi Minh city
 
Sap s4 hana 1709 op sap api-master guide
Sap s4 hana 1709 op sap api-master guideSap s4 hana 1709 op sap api-master guide
Sap s4 hana 1709 op sap api-master guidemutia_arum
 
Sg247692 Websphere Accounting Chargeback For Tuam Guide
Sg247692 Websphere Accounting Chargeback For Tuam GuideSg247692 Websphere Accounting Chargeback For Tuam Guide
Sg247692 Websphere Accounting Chargeback For Tuam Guidebrzaaap
 
BOOK - IBM tivoli netcool service quality manager data mediation gateway deve...
BOOK - IBM tivoli netcool service quality manager data mediation gateway deve...BOOK - IBM tivoli netcool service quality manager data mediation gateway deve...
BOOK - IBM tivoli netcool service quality manager data mediation gateway deve...Satya Harish
 
Enabling mobile apps with ibm worklight application center red
Enabling mobile apps with ibm worklight application center redEnabling mobile apps with ibm worklight application center red
Enabling mobile apps with ibm worklight application center redbupbechanhgmail
 
Ibm tivoli monitoring for network performance v2.1 the mainframe network mana...
Ibm tivoli monitoring for network performance v2.1 the mainframe network mana...Ibm tivoli monitoring for network performance v2.1 the mainframe network mana...
Ibm tivoli monitoring for network performance v2.1 the mainframe network mana...Banking at Ho Chi Minh city
 

Similar to DBMS_Lab_Manual_&_Solution (20)

programación en prolog
programación en prologprogramación en prolog
programación en prolog
 
Ibm tivoli intelligent think dynamic orchestrator pre proof of-concept cookbo...
Ibm tivoli intelligent think dynamic orchestrator pre proof of-concept cookbo...Ibm tivoli intelligent think dynamic orchestrator pre proof of-concept cookbo...
Ibm tivoli intelligent think dynamic orchestrator pre proof of-concept cookbo...
 
Swi prolog-6.2.6
Swi prolog-6.2.6Swi prolog-6.2.6
Swi prolog-6.2.6
 
BOOK - IBM Implementing ibm system directory 6.1
BOOK - IBM Implementing ibm system directory 6.1BOOK - IBM Implementing ibm system directory 6.1
BOOK - IBM Implementing ibm system directory 6.1
 
Systems se
Systems seSystems se
Systems se
 
bkremer-report-final
bkremer-report-finalbkremer-report-final
bkremer-report-final
 
Jdbc
JdbcJdbc
Jdbc
 
OpenScape Contact Center Enterprise V10 Manager Administration Guide Administ...
OpenScape Contact Center Enterprise V10 Manager Administration Guide Administ...OpenScape Contact Center Enterprise V10 Manager Administration Guide Administ...
OpenScape Contact Center Enterprise V10 Manager Administration Guide Administ...
 
Modifying infor erp_syte_line_5140
Modifying infor erp_syte_line_5140Modifying infor erp_syte_line_5140
Modifying infor erp_syte_line_5140
 
Deployment guide series ibm tivoli usage and accounting manager v7.1 sg247569
Deployment guide series ibm tivoli usage and accounting manager v7.1 sg247569Deployment guide series ibm tivoli usage and accounting manager v7.1 sg247569
Deployment guide series ibm tivoli usage and accounting manager v7.1 sg247569
 
Certification guide series ibm tivoli provisioning manager v5.1 sg247262
Certification guide series ibm tivoli provisioning manager v5.1 sg247262Certification guide series ibm tivoli provisioning manager v5.1 sg247262
Certification guide series ibm tivoli provisioning manager v5.1 sg247262
 
Solution deployment guide for ibm tivoli composite application manager for we...
Solution deployment guide for ibm tivoli composite application manager for we...Solution deployment guide for ibm tivoli composite application manager for we...
Solution deployment guide for ibm tivoli composite application manager for we...
 
Sap s4 hana 1709 op sap api-master guide
Sap s4 hana 1709 op sap api-master guideSap s4 hana 1709 op sap api-master guide
Sap s4 hana 1709 op sap api-master guide
 
Sg247692 Websphere Accounting Chargeback For Tuam Guide
Sg247692 Websphere Accounting Chargeback For Tuam GuideSg247692 Websphere Accounting Chargeback For Tuam Guide
Sg247692 Websphere Accounting Chargeback For Tuam Guide
 
Performance tuning for content manager sg246949
Performance tuning for content manager sg246949Performance tuning for content manager sg246949
Performance tuning for content manager sg246949
 
Srs
SrsSrs
Srs
 
BOOK - IBM tivoli netcool service quality manager data mediation gateway deve...
BOOK - IBM tivoli netcool service quality manager data mediation gateway deve...BOOK - IBM tivoli netcool service quality manager data mediation gateway deve...
BOOK - IBM tivoli netcool service quality manager data mediation gateway deve...
 
test6
test6test6
test6
 
Enabling mobile apps with ibm worklight application center red
Enabling mobile apps with ibm worklight application center redEnabling mobile apps with ibm worklight application center red
Enabling mobile apps with ibm worklight application center red
 
Ibm tivoli monitoring for network performance v2.1 the mainframe network mana...
Ibm tivoli monitoring for network performance v2.1 the mainframe network mana...Ibm tivoli monitoring for network performance v2.1 the mainframe network mana...
Ibm tivoli monitoring for network performance v2.1 the mainframe network mana...
 

More from Syed Zaid Irshad

More from Syed Zaid Irshad (20)

Operating System.pdf
Operating System.pdfOperating System.pdf
Operating System.pdf
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptx
 
Professional Issues in Computing
Professional Issues in ComputingProfessional Issues in Computing
Professional Issues in Computing
 
Reduce course notes class xi
Reduce course notes class xiReduce course notes class xi
Reduce course notes class xi
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
 
Introduction to Database
Introduction to DatabaseIntroduction to Database
Introduction to Database
 
C Language
C LanguageC Language
C Language
 
Flowchart
FlowchartFlowchart
Flowchart
 
Algorithm Pseudo
Algorithm PseudoAlgorithm Pseudo
Algorithm Pseudo
 
Computer Programming
Computer ProgrammingComputer Programming
Computer Programming
 
ICS 2nd Year Book Introduction
ICS 2nd Year Book IntroductionICS 2nd Year Book Introduction
ICS 2nd Year Book Introduction
 
Security, Copyright and the Law
Security, Copyright and the LawSecurity, Copyright and the Law
Security, Copyright and the Law
 
Computer Architecture
Computer ArchitectureComputer Architecture
Computer Architecture
 
Data Communication
Data CommunicationData Communication
Data Communication
 
Information Networks
Information NetworksInformation Networks
Information Networks
 
Basic Concept of Information Technology
Basic Concept of Information TechnologyBasic Concept of Information Technology
Basic Concept of Information Technology
 
Introduction to ICS 1st Year Book
Introduction to ICS 1st Year BookIntroduction to ICS 1st Year Book
Introduction to ICS 1st Year Book
 
Using the set operators
Using the set operatorsUsing the set operators
Using the set operators
 
Using subqueries to solve queries
Using subqueries to solve queriesUsing subqueries to solve queries
Using subqueries to solve queries
 

Recently uploaded

ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...liera silvan
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEaurabinda banchhor
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 

Recently uploaded (20)

ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSE
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 

DBMS_Lab_Manual_&_Solution

  • 1. Database Management System Lab Manual Engr. Syed Zaid Irshad This document contains Lab Theory and Tasks It is up to the instructor how he/she divides tasks among each Labs Department of Computer Science Mohammad Ali Jinnah University, Karachi Pakistan January 11, 2023
  • 2. 2
  • 3. Contents 1 Visual Studio 5 1.1 About Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.1.1 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.1.2 History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.1.3 Why you should choose Visual Studio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.2 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.3 Simple Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 1.4 Simple Countdown Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 1.5 User Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 2 SQL Server & SQL Server Management Studio 27 2.1 About Software’s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 2.1.1 Version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 2.1.2 Edition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 2.1.3 Key Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 2.2 Basics of SQL Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 2.2.1 Statement Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 2.2.2 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 2.2.3 Predicates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 2.2.4 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 2.2.5 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 2.2.6 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 2.2.7 Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 2.3 Levels of Severity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 2.4 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 2.5 Create New Login . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 3 Transact-SQL Statements (Basic) 45 3.1 Load Data-set on SQL Server Management Studio . . . . . . . . . . . . . . . . . . . . . . . . . . 45 3.2 DML (Data Manipulation Language) Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 3.3 Data Definition Language (DDL) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 3.3.1 Procedure/Variables for Existing Database . . . . . . . . . . . . . . . . . . . . . . . . . . 78 3.3.2 Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 3.3.3 Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 3.3.4 Column . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 4 School Management System 91 4.1 ER-Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 4.2 Database Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 4.3 User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 5 Transact-SQL Statements (Intermediate) 117 5.1 Joins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 5.2 Variables and Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 5.3 Sub-queries and Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 5.4 Program Flow Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 5.5 Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 5.6 Triggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 3
  • 4. 4 CONTENTS 6 Malicious 147 6.1 Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 6.2 Create Setup File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 A Lab Details 165
  • 5. Chapter 1 Visual Studio 1.1 About Software • Visual Studio is an integrated development environment (IDE) from Microsoft. • It is used to develop computer programs, as well as websites, web apps, web services and mobile apps. • Visual Studio uses Microsoft software development platforms such as Windows API, Windows Forms, Windows Presentation Foundation, Windows Store and Microsoft Silverlight. • It can produce both native codes and managed code. • Visual Studio includes a code editor supporting IntelliSense (the code completion component) as well as code refactoring. • The integrated debugger works both as a source-level debugger and a machine-level debugger. • Other built-in tools include a code profiler, a designer for building GUI applications, a web designer, a class designer, and a database schema designer. • It accepts plug-ins that expand the functionality at almost every level—including adding support for source control systems (like Subversion and Git) and adding new toolsets like editors and visual designers for domain-specific languages or toolsets for other aspects of the software development lifecycle (like the Azure DevOps client: Team Explorer). • Visual Studio supports 36 different programming languages and allows the code editor and debugger to support (to varying degrees) nearly any programming language, provided a language-specific service exists. • Built-in languages include C, Cplusplus, Cplusplus/CLI, Visual Basic .NET, C#, F#, JavaScript, TypeScript, XML, XSLT, HTML, and CSS. • Support for other languages such as Python, Ruby, Node.js, and M among others is available via plug-ins. • Java (and J#) were supported in the past. • The most basic edition of Visual Studio, the Community edition, is available free of charge. The slogan for Visual Studio Community edition is ”Free, fully-featured IDE for students, open-source and individual developers”. 1.1.1 Features Visual Studio provides the most advanced features that the latest developers are looking for. A few of the most important features are described as follows: 1. Code Editor: Visual Studio has the best-in-class Code editor which supports multiple functionalities. It enables bookmarks in code to incorporate Quick Navigation. In addition to the normal text, VS also provides Incremental Search, Regex Search, Multi-item Clipboard, and Task-list. The Editor is also capable to support Code refactoring, Parameter Reordering, Variable and Method Renaming, Interface Extraction and many more user-friendly functionalities. 5
  • 6. 6 CHAPTER 1. VISUAL STUDIO 2. Debugger: The remarkable Debugger of MS Visual Studio can work both as a Machine Level Debugger as well as a Source Level Debugger. It is capable to debug Mapped Code as well as Native Code. It is capable to compile any programming language that supports VS. It is capable to attach itself to the currently running process to conduct monitoring and debugging procedures on the code, provided the source code is available. VS can incorporate Memory Dumps and Multi-threading as well. 3. Designer: Visual Studio includes several visual designers to help with the development of applications. Some of the tools are listed below. (a) WPS authorizes user interfaces for Windows Presentation Foundation. (b) Windows Forms designer creates GUI applications using Windows Forms. (c) The Class Designer authorises and edits the classes including its members and their access using UML modelling. (d) Visual Studio additionally includes a website editor and designer that permits websites to be authored by dragging and dropping widgets. (e) Mapping designer is employed by LINQ to SQL to design the mapping between information schema and therefore the classes that encapsulate the data. (f) The data designer is used to graphically edit information schema, as well as written tables, primary and foreign keys and constraints. 4. Other Tools (a) Properties editor edits the properties in the GUI in VS. (b) It enlists all the properties available for classes, objects, and web pages. (c) Server Explorer manages Database connections on a computer. (d) Object browser is used to browse the namespaces in managed assemblies. (e) Team Explorer Integrates the Axure DevOps Into the VS IDE. (f) Data Explorer manages MS SQL databases and instances. (g) Solution Explorer manages and browses the files in a solution. 5. Extensibility Visual Studio permits developers to write down extensions for Visual Studio to extend its capabilities. These extensions “plug into” Visual Studio and extend its functionality. Extensions are available in the form of macros, add-ins, and packages. 1.1.2 History Product name Code name Release date Support Ends Visual Studio 2022 Dev17 08/11/2021 January 13, 2032 Visual Studio 2019 Dev16 02/04/2019 April 10, 2029 Visual Studio 2017 Dev15 07/03/2017 April 13, 2027 Visual Studio 2015 Dev14 20/07/2015 October 14, 2025 Visual Studio 2013 Dev12 17/10/2013 April 9, 2024 Visual Studio 2012 Dev11 12/09/2012 January 10, 2023 Visual Studio 2010 Dev10 12/04/2010 July 14, 2020 Visual Studio 2008 Orcas 19/11/2007 April 10, 2018 Visual Studio 2005 Whidbey 07/11/2005 April 12, 2016 Visual Studio .NET 2003 Everett 24/04/2003 October 8, 2013 Visual Studio .NET (2002) Rainier 13/02/2002 July 14, 2009 Visual Studio 6.0 Aspen 02/09/1998 September 30, 2005 Visual Studio 97 Boston 19/03/1997 June 30, 2003 1.1.3 Why you should choose Visual Studio • Visual Studio is functionally feature-rich. In most cases, Visual Code matches the requirements of most developers perfectly without having to rely on further extensions or plugins.
  • 7. 1.2. INSTALLATION 7 • In Visual Studio, collaborating with your entire team is pretty easy when it comes to development as well as debugging code. The workflow is super-smooth and is loaded with all kinds of features one would need in the long run. • When it comes to heavy-duty code analysis, debugging as well as performance profiling, Visual Studio is an incredible option. • Visual Studio is pretty commonly used in the game development industry. For instance, UNITY, a multi-platform environment integrated with Visual Studio, can work effortlessly to build cross-platform mobile gaming applications, AR/VR applications, and more! Organizations using Visual Studio for development Useful Link for Students: https://visualstudio.microsoft.com/students/ 1.2 Installation 1. Download software from the link.
  • 8. 8 CHAPTER 1. VISUAL STUDIO 2. Open the software by double-clicking on it. 3. Select ASP.NET and web development, Data Storage and Processing, and .Net Desktop Development from Workloads.
  • 9. 1.2. INSTALLATION 9 4. Select .Net 6.0 Runtime, .Net Core 3.1 Runtime (LST), .Net Framework 4.6.2 targeting pack, and .Net Framework 4.7 targeting pack from Individual Components. Press the Install button on the bottom right corner. Wait for the installation to complete. 5. Press the Launch button.
  • 10. 10 CHAPTER 1. VISUAL STUDIO 6. Sign in using your Microsoft account. 7. Select Development Settings to General. Choose a Theme colour if you wish. Press Start Visual Studio Button.
  • 11. 1.3. SIMPLE APPLICATION 11 1.3 Simple Application 1. Open Visual Studio, Select Create a new Project 2. Choose Windows Form Application (.NET Framework), Press Next
  • 12. 12 CHAPTER 1. VISUAL STUDIO 3. Type Name and press Create 4. Select Textbox and Button from Common Control in Toolbox
  • 13. 1.3. SIMPLE APPLICATION 13 5. Rename Button and Double click on it. 6. type: MessageBox.Show(textBox1.Text); in button1 Click
  • 14. 14 CHAPTER 1. VISUAL STUDIO 7. Press Start from Ribbon 8. Type String and Press Button
  • 15. 1.4. SIMPLE COUNTDOWN APPLICATION 15 1.4 Simple Countdown Application 1. Open Visual Studio, Select Create a new Project, Choose Windows Form Application (.NET Framework), Press Next 2. Type Name and press Create
  • 16. 16 CHAPTER 1. VISUAL STUDIO 3. Select Textbox and 2 Buttons from Common Control in Toolbox 4. Rename Buttons (Start, Pause) and Double click on them.
  • 17. 1.4. SIMPLE COUNTDOWN APPLICATION 17 5. Search Timer in Toolbox and add it to the project. 6. Type Following Code in .cs file namespace CountdownTimer { public partial class Form1 : Form { public Form1() { InitializeComponent(); } int second; private void button1_Click(object sender, EventArgs e) { timer1.Start(); } private void button3_Click(object sender, EventArgs e) { timer1.Stop(); label2.Text = "Paused"; } private void timer1_Tick(object sender, EventArgs e) { if (second > 0) { second = second - 1; label2.Text = second.ToString() + " Second(s)"; } else { timer1.Stop(); label2.Text = "Times Up"; } } private void textBox3_TextChanged(object sender, EventArgs e) { second = Convert.ToInt32(textBox3.Text); } } }
  • 18. 18 CHAPTER 1. VISUAL STUDIO 7. Press Start from Ribbon, Type Time and Press Start Button 1.5 User Information 1. Open Visual Studio, Select Create a new Project
  • 19. 1.5. USER INFORMATION 19 2. Choose Windows Form Application (.NET Framework), Press Next 3. Type Name and press Create
  • 20. 20 CHAPTER 1. VISUAL STUDIO 4. Change the form’s name from ”Form1.cs” to ”UserInfo.cs”. 5. Clicking the form’s title bar, navigate to the Properties window and set the Size property’s Width to 455 and Height to 251.
  • 21. 1.5. USER INFORMATION 21 6. Drag a Label control onto the form; select this control, navigate to the Properties window, and set the Name property to CountryLabel, AutoSize property to false, Location property’s X to 12 and Y to 26, Size property’s Width to 71 and Height to 15, Text property to Enter Country. 7. Drag a TextBox control in front of the Country label. Select this control, navigate to the Properties window, and set the Name property to Country, Location property’s X to 97 and Y to 19, Size property’s Width to 129 and Height to 23.
  • 22. 22 CHAPTER 1. VISUAL STUDIO 8. Drag another Label below Country, select this control, navigate to the Properties window, and set the Name property to StateLabel, the AutoSize property to false, the Location property’s X to 12 and Y to 65, Size property’s Width to 60 and Height to 15, Text property to Enter State. 9. Drag a TextBox control in front of the State label. Select this control, navigate to the Properties window, and set the Name property to State, Location property’s X to 97 and Y to 58, Size property’s Width to 129 and Height to 23.
  • 23. 1.5. USER INFORMATION 23 10. Drag a ListBox control onto the UserInfo form on the right side of the TextBox control you have added. Select this control, navigate to the Properties window, and set the Name property to CountryList, Location property’s X to 280 and Y to 12, Size property’s Width to 129 and Height to 79. 11. Drag a ComboBox below the ListBox that you just added. Select this control, navigate to the Properties window, and set the Name property to StateCB, Location property’s X to 280 and Y to 117, Size property’s Width to 129 and Height to 23.
  • 24. 24 CHAPTER 1. VISUAL STUDIO 12. Drag two CheckBoxes below the Label controls, and name them PostalMail (location 97, 117) and Email (location 97, 142); set their Text property to Postal Mail and E-Mail, respectively. 13. Drag two RadioButtons below the TextBox controls, and name Male (location 97, 178) and Female (location 97, 203); set their Text property to Male and Female, respectively.
  • 25. 1.5. USER INFORMATION 25 14. Drag a Button control to the UserInfo form to the left side below the CheckBox controls; select this control, navigate to the Properties window, and set the Name property to Add, Location property’s X to 65 and Y to 88, Size property’s Width to 95 and Height to 23, Text property to Add. 15. Drag a Button control next to the Add button; select this control, navigate to the Properties window, and set the Name property to RemoveCountry, Location property’s X to 166 and Y to 87, Size property’s Width to 95 and Height to 23, Text property to Remove Country.
  • 26. 26 CHAPTER 1. VISUAL STUDIO 16. Drag a Button control, navigate to the Properties window, and set the Name property to ShowDetails, Location property’s X to 415 and Y to 117, Size property’s Width to 90 and Height to 23, Text property to Show Details. 17. Type the following Code in the .cs file namespace UserInformation { public partial class UserInfo : Form { public UserInfo() { InitializeComponent(); } private void addCountry_Click(object sender, EventArgs e) { CountryList.Items.Add(Country.Text); Country.Clear(); StateCB.Items.Add(State.Text); State.Clear(); } private void RemoveCountry_Click(object sender, EventArgs e) { CountryList.Items.Remove(CountryList.SelectedItem); } private void showDetail_Click(object sender, EventArgs e) { if (Email.Checked == true || Postmail.Checked == true && male.Checked == true) { MessageBox.Show("Hello Mr, you will be contacted by either USPS or email", "Information",MessageBoxButtons.OKCancel, MessageBoxIcon.Information); } else if (Email.Checked == true || Postmail.Checked == true && female.Checked == true) { MessageBox.Show("Hello Mam, you will be contacted by either USPS or email", "Information",MessageBoxButtons.OKCancel, MessageBoxIcon.Information); } } } }
  • 27. Chapter 2 SQL Server & SQL Server Management Studio 2.1 About Software’s • Microsoft SQL Server is a relational database management system developed by Microsoft. • As a database server, it is a software product with the primary function of storing and retrieving data as requested by other software applications—which may run either on the same computer or on another computer across a network (including the Internet). • Microsoft markets at least a dozen different editions of Microsoft SQL Server, aimed at different audiences and for workloads ranging from small single-machine applications to large Internet-facing applications with many concurrent users. • SQL Server Management Studio (SSMS) is an IDE that provides a graphical interface for connecting and working with MS SQL server. • It was launched with Microsoft SQL Server 2005 and is used for configuring, managing, and administering all components within Microsoft SQL Server. 2.1.1 Version • SQL Server – Microsoft and Sybase released version 1.0 in 1989. – However, the partnership between these two ended in the early 1990s. – Microsoft maintained ownership rights to the name SQL Server. – Since the 1990s, subsequent versions of SQL Server have been released including SQL Server 2000, 2005, 2008, 2012, 2014, 2016, 2017, and 2019. • SQL Server Management Studio – SSMS first version was with SQL server 2005. – SSMS remains an integral part of SQL server with SQL Server 2008, SQL Server 2012 and SQL Server 2016. – In 2016, Microsoft started the first numerical series of versioning with the SSMS version number 16.3. – All series include 16.x, 17.x and 18.0 as version numbers. 2.1.2 Edition • SQL Server – SQL Server Enterprise: It is used in high-end, large scale and mission-critical businesses. It provides High-end security, Advanced analytics, Machine Learning, etc. 27
  • 28. 28 CHAPTER 2. SQL SERVER & SQL SERVER MANAGEMENT STUDIO – SQL Server Standard: It is suitable for Mid-Tier Applications and Data Marts. It includes basic reporting and analytics. – SQL Server WEB: It is designed for a low total cost-of-ownership option for Web hosters. It provides scalability, affordability, and manageability capabilities for small to large-scale Web properties. – SQL Server Developer: It is similar to an enterprise edition for the non-production environment. It is mainly used for build, testing, and demoing. – SQL Server Express: It is for small-scale applications and is free to use. 2.1.3 Key Components • SQL Server – Database Engine: This component handle storage, Rapid transaction Processing, and Securing Data. – SQL Server: This service starts, stops, pauses, and continues an instance of Microsoft SQL Server. The executable name is sqlservr.exe. – SQL Server Agent: It performs the role of Task Scheduler. It can be triggered by any event or as per demand. The executable name is sqlagent.exe. – SQL Server Browser: This listens to the incoming request and connects to the desired SQL server instance. The executable name is sqlbrowser.exe. – SQL Server Full-Text Search: This lets the user run full-text queries against Character data in SQL Tables. The executable name is fdlauncher.exe. – SQL Server VSS Writer: This allows backup and restoration of data files when the SQL server is not running. The executable name is sqlwriter.exe. – SQL Server Analysis Services (SSAS): Provide Data analysis, Data mining and Machine Learning capabilities. SQL server is integrated with R and Python language for advanced analytics. The executable name is msmdsrv.exe. – SQL Server Reporting Services (SSRS): Provides reporting features and decision-making capabilities. It includes integration with Hadoop. The executable name is ReportingServicesService.exe. – SQL Server Integration Services (SSIS): Provided Extract-Transform and Load capabilities of the different types of data from one source to another. It can be viewed as converting raw information into useful information. The executable name is MsDtsSrvr.exe. 2.2 Basics of SQL Server 2.2.1 Statement Types • Data Definition Language (DDL) – CREATE – ALTER – DROP • Data Manipulation Language (DML) – SELECT – INSERT – UPDATE – DELETE • Data Control Language (DCL) – GRANT – REVOKE – DENY
  • 29. 2.2. BASICS OF SQL SERVER 29 2.2.2 Data Types • String – char(n) - Fixed width character string – varchar(n) - Variable width character string – varchar(max) - Variable width character string – text - Variable width character string – nchar - Fixed width Unicode string – nvarchar - Variable width Unicode string – nvarchar(max) - Variable width Unicode string – ntext - Variable width Unicode string – binary(n) - Fixed width binary string – varbinary - Variable width binary string – varbinary(max) - Variable width binary string – image - Variable width binary string 2GB • Numeric – bit - Integer that can be 0, 1, or NULL – tinyint - Allows whole numbers from 0 to 255 – smallint - Allows whole numbers between -32,768 and 32,767 – int - Allows whole numbers between -2,147,483,648 and 2,147,483,647 – bigint - Allows whole numbers between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 – decimal(p,s) - Fixed precision and scale numbers. – numeric(p,s) - Fixed precision and scale numbers. – smallmoney - Monetary data from -214,748.3648 to 214,748.3647 – money - Monetary data from -922,337,203,685,477.5808 to 922,337,203,685,477.5807 – float(n) - Floating precision number data from -1.79E + 308 to 1.79E + 308. – real - Floating precision number data from -3.40E + 38 to 3.40E + 38 4 bytes • Date and Time – datetime - From January 1, 1753 to December 31, 9999 with an accuracy of 3.33 milliseconds – datetime2 - From January 1, 0001 to December 31, 9999 with an accuracy of 100 nanoseconds 6-8 bytes – smalldatetime - From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute – date - Store a date only. From January 1, 0001 to December 31, 9999 – time - Store a time only to an accuracy of 100 nanoseconds – datetimeoffset - The same as datetime2 with the addition of a time zone offset – timestamp - Stores a unique number that gets updated every time a row gets created or modified. The timestamp value is based upon an internal clock and does not correspond to real-time. Each table may have only one timestamp variable 2.2.3 Predicates A predicate is an expression that evaluates to TRUE, FALSE, or UNKNOWN. • IN - Determines whether a specified value matches any value in a sub-query or a list. • BETWEEN - Specifies a range of values to test.
  • 30. 30 CHAPTER 2. SQL SERVER & SQL SERVER MANAGEMENT STUDIO • LIKE - Used to match characters against a specified pattern. • CONTAINS - Searches for precise or less precise matches to single words and phrases, words within a certain distance of one another, or weighted matches. ALL TRUE if all of the subquery values meet the condition • AND - TRUE if all the conditions separated by AND is TRUE • ANY - TRUE if any of the subquery values meet the condition • EXISTS - TRUE if the subquery returns one or more records • NOT - Displays a record if the condition(s) is NOT TRUE • OR - TRUE if any of the conditions separated by OR is TRUE • SOME - TRUE if any of the subquery values meet the condition 2.2.4 Operators • Arithmetic – Add (+) – Subtract (-) – Multiply (*) – Divide (/) – Modulo (%) • Bitwise – AND (&) – OR (|) – Exclusive OR (∧) • Comparison – Equal to (=) – Greater than (>) – Less than (<) – Greater than or equal to (>=) – Less than or equal to (<=) – Not equal to (<>) • Compound – Add equals (+=) – Subtract equals (-=) – Multiply equals (*=) – Divide equals (/=) – Modulo equals (%=) – Bitwise AND equals (&=) – Bitwise exclusive equals (∧=) – Bitwise OR equals (| =) 2.2.5 Comments • Single Line (−−Comment) • Multi-line (/* Comments */)
  • 31. 2.2. BASICS OF SQL SERVER 31 2.2.6 Functions • String – ASCII(character) - The ASCII() function returns the ASCII value for the specific character. – CHAR(code) - The CHAR() function returns the character based on the ASCII code. – CHARINDEX(substring, string, start) - The CHARINDEX() function searches for a substring in a string, and returns the position. – CONCAT(string1, string2, ...., string n) - The CONCAT() function adds two or more strings together. – string1 + string2 + string n - The + operator allows you to add two or more strings together. – CONCAT WS(separator, string1, string2, ...., string n) - The CONCAT WS() function adds two or more strings together with a separator. – DATALENGTH(expression) - The DATALENGTH() function returns the number of bytes used to represent an expression. – DIFFERENCE(expression, expression) - The DIFFERENCE() function compares two SOUNDEX values, and returns an integer. The integer value indicates the match for the two SOUNDEX values, from 0 to 4. – FORMAT(value, format, culture) - The FORMAT() function formats a value with the specified format. – LEFT(string, number of chars) - The LEFT() function extracts a number of characters from a string (starting from left). – LEN(string) - The LEN() function returns the length of a string. – LOWER(text) - The LOWER() function converts a string to lower-case. – LTRIM(string) - The LTRIM() function removes leading spaces from a string. – NCHAR(number code) - The NCHAR() function returns the Unicode character based on the number code. – PATINDEX(%pattern%, string) - The PATINDEX() function returns the position of a pattern in a string. – QUOTENAME(string, quote char) - The QUOTENAME() function returns a Unicode string with delimiters added to make the string a valid SQL Server delimited identifier. – REPLACE(string, old string, new string) - The REPLACE() function replaces all occurrences of a substring within a string, with a new substring. – REPLICATE(string, integer) - The REPLICATE() function repeats a string a specified number of times. – REVERSE(string) - The REVERSE() function reverses a string and returns the result. – RIGHT(string, number of chars) - The RIGHT() function extracts a number of characters from a string (starting from the right). – RTRIM(string) - The RTRIM() function removes trailing spaces from a string. – SOUNDEX(expression) - The SOUNDEX() function returns a four-character code to evaluate the similarity of two expressions. – SPACE(number) - The SPACE() function returns a string of the specified number of space characters. – STR(number, length, decimals) - The STR() function returns a number as a string. – STUFF(string, start, length, new string) - The STUFF() function deletes a part of a string and then inserts another part into the string, starting at a specified position. – SUBSTRING(string, start, length) - The SUBSTRING() function extracts some characters from a string. – TRANSLATE(string, characters, translations) - The TRANSLATE() function returns the string from the first argument after the characters specified in the second argument are translated into the characters specified in the third argument.
  • 32. 32 CHAPTER 2. SQL SERVER & SQL SERVER MANAGEMENT STUDIO – TRIM([characters FROM ]string) - The TRIM() function removes the space character OR other specified characters from the start or end of a string. – UNICODE(character expression) - The UNICODE() function returns an integer value (the Unicode value), for the first character of the input expression. – UPPER(text) - The UPPER() function converts a string to upper-case. • Math/Numeric – ABS(number) - The ABS() function returns the absolute value of a number. – ACOS(number) - The ACOS() function returns the arc cosine of a number. – ASIN(number) - The ASIN() function returns the arc sine of a number. – ATAN(number) - The ATAN() function returns the arc tangent of a number. – ATN2(a, b) - The ATN2() function returns the arc tangent of two numbers. – AVG(expression) - The AVG() function returns the average value of an expression. – CEILING(number) - The CEILING() function returns the smallest integer value that is larger than or equal to a number. – COUNT(expression) - The COUNT() function returns the number of records returned by a select query. – COS(number) - The COS() function returns the cosine of a number. – COT(number) - The COT() function returns the cotangent of a number. – DEGREES(number) - The DEGREES() function converts a value in radians to degrees. – EXP(number) - The EXP() function returns e raised to the power of a specified number. – FLOOR(number) - The FLOOR() function returns the largest integer value that is smaller than or equal to a number. – LOG(number, base) - The LOG() function returns the natural logarithm of a specified number or the logarithm of the number to the specified base. – LOG10(number) - The LOG10() function returns the natural logarithm of a number to base 10. – MAX(expression) - The MAX() function returns the maximum value in a set of values. – MIN(expression) - The MIN() function returns the minimum value in a set of values. – PI() - The PI() function returns the value of PI. – POWER(a, b) - The POWER() function returns the value of a number raised to the power of another number. – RADIANS(number) - The RADIANS() function converts a degree value into radians. – RAND(seed) - The RAND() function returns a random number between 0 (inclusive) and 1 (exclusive). – ROUND(number, decimals, operation) - The ROUND() function rounds a number to a specified number of decimal places. – SIGN(number) - The SIGN() function returns the sign of a number. – SIN(number) - The SIN() function returns the sine of a number. – SQRT(number) - The SQRT() function returns the square root of a number. – SQUARE(number) - The SQUARE() function returns the square of a number. – SUM(expression) - The SUM() function calculates the sum of a set of values. – TAN(number) - The TAN() function returns the tangent of a number. • Date – CURRENT TIMESTAMP - The CURRENT TIMESTAMP function returns the current date and time, in a ’YYYY-MM-DD hh:mm:ss.mmm’ format.
  • 33. 2.2. BASICS OF SQL SERVER 33 – DATEADD(interval, number, date) - The DATEADD() function adds a time/date interval to a date and then returns the date. – DATEDIFF(interval, date1, date2) - The DATEDIFF() function returns the difference between two dates. – DATEFROMPARTS(year, month, day) - The DATEFROMPARTS() function returns a date from the specified parts (year, month, and day values). – DATENAME(interval, date) - The DATENAME() function returns a specified part of a date. – DATEPART(interval, date) - The DATEPART() function returns a specified part of a date. – DAY(date) - The DAY() function returns the day of the month (from 1 to 31) for a specified date. – GETDATE() - The GETDATE() function returns the current database system date and time, in a ’YYYY-MM-DD hh:mm:ss.mmm’ format. – GETUTCDATE() - The GETUTCDATE() function returns the current database system UTC date and time, in a ’YYYY-MM-DD hh:mm:ss.mmm’ format. – ISDATE(expression) - The ISDATE() function checks an expression and returns 1 if it is a valid date, otherwise 0. – MONTH(date) - The MONTH() function returns the month part for a specified date (a number from 1 to 12). – SYSDATETIME() - The SYSDATETIME() function returns the date and time of the computer where the SQL Server is running. – YEAR(date) - The YEAR() function returns the year part for a specified date. • Advance – CAST(expression AS datatype(length)) - The CAST() function converts a value (of any type) into a specified datatype. – COALESCE(val1, val2, ...., valn) - The COALESCE() function returns the first non-null value in a list. – CONVERT(data type(length), expression, style) - The CONVERT() function converts a value (of any type) into a specified datatype. – CURRENT USER - The CURRENT USER function returns the name of the current user in the SQL Server database. – IIF(condition, value if true, value if false) - The IIF() function returns a value if a condition is TRUE, or another value if a condition is FALSE. – ISNULL(expression, value) - The ISNULL() function returns a specified value if the expression is NULL. – ISNUMERIC(expression) - The ISNUMERIC() function tests whether an expression is numeric. – NULLIF(expr1, expr2) - The NULLIF() function returns NULL if two expressions are equal, otherwise, it returns the first expression. – SESSION USER - The SESSION USER function returns the name of the current user in the SQL Server database. – SESSIONPROPERTY(option) - The SESSIONPROPERTY() function returns the session settings for a specified option. – SYSTEM USER - The SYSTEM USER function returns the login name for the current user. – USER NAME(id number) - The USER NAME() function returns the database user name based on the specified id. 2.2.7 Control Flow • BEGIN sql statement — statement block END • BREAK
  • 34. 34 CHAPTER 2. SQL SERVER & SQL SERVER MANAGEMENT STUDIO • CONTINUE • IF Boolean expression sql statement — statement block [ ELSE sql statement — statement block ] • RETURN [ integer expression ] • THROW [ error number — @local variable , message — @local variable , state — @local variable ] • BEGIN TRY sql statement — statement block END TRY BEGIN CATCH [ sql statement — state- ment block ] END CATCH • WHILE Boolean expression sql statement — statement block — BREAK — CONTINUE 2.3 Levels of Severity • 0-9: Informational messages that return status information or report errors that are not severe. The Database Engine does not raise system errors with severities of 0 through 9. • 10: Informational messages that return status information or report errors that are not severe. For compatibility reasons, the Database Engine converts severity 10 to severity 0 before returning the error information to the calling application. • 11-16: Indicate errors that can be corrected by the user. 1. 11: Indicates that the given object or entity does not exist. 2. 12: A special severity for queries that do not use locking because of special query hints. In some cases, read operations performed by these statements could result in inconsistent data since locks are not taken to guarantee consistency. 3. 13: Indicates transaction deadlock errors. 4. 14: Indicates security-related errors, such as permission denied. 5. 15: Indicates syntax errors in the Transact-SQL command. 6. 16: Indicates general errors that can be corrected by the user. • 17-19: Indicate software errors that cannot be corrected by the user. Inform your system administrator of the problem. 1. 17: Indicates that the statement caused SQL Server to run out of resources (such as memory, locks, or disk space for the database) or to exceed some limit set by the system administrator. 2. 18: Indicates a problem in the Database Engine software, but the statement completes execution, and the connection to the instance of the Database Engine is maintained. The system administrator should be informed every time a message with a severity level of 18 occurs. 3. 19: Indicates that a non-configurable Database Engine limit has been exceeded and the current batch process has been terminated. Error messages with a severity level of 19 or higher stop the execution of the current batch. Severity level 19 errors are rare and must be corrected by the system administrator or your primary support provider. Contact your system administrator when a message with a severity level 19 is raised. Error messages with a severity level from 19 through 25 are written to the error log. • 20-24 Indicate system problems and are fatal errors, which means that the Database Engine task that is executing a statement or batch is no longer running. The task records information about what occurred and then terminates. In most cases, the application connection to the instance of the Database Engine may also terminate. If this happens, depending on the problem, the application might not be able to reconnect. Error messages in this range can affect all of the processes accessing data in the same database and may indicate that a database or object is damaged. Error messages with a severity level from 19 through 24 are written to the error log. 1. 20: Indicates that a statement has encountered a problem. Because the problem has affected only the current task, it is unlikely that the database itself has been damaged. 2. 21: Indicates that a problem has been encountered that affects all tasks in the current database, but it is unlikely that the database itself has been damaged. 3. 22: Indicates that the table or index specified in the message has been damaged by a software or hardware problem. Severity level 22 errors occur rarely. If one occurs, run DBCC CHECKDB to determine whether other objects in the database are also damaged. The problem might be in the
  • 35. 2.4. INSTALLATION 35 buffer cache only and not on the disk itself. If so, restarting the instance of the Database Engine corrects the problem. To continue working, you must reconnect to the instance of the Database Engine; otherwise, use DBCC to repair the problem. In some cases, you may have to restore the database. If restarting the instance of the Database Engine does not correct the problem, then the problem is on the disk. Sometimes destroying the object specified in the error message can solve the problem. For example, if the message reports that the instance of the Database Engine has found a row with a length of 0 in a nonclustered index, delete the index and rebuild it. 4. 23: Indicates that the integrity of the entire database is in question because of a hardware or software problem. Severity level 23 errors occur rarely. If one occurs, run DBCC CHECKDB to determine the extent of the damage. The problem might be in the cache only and not on the disk itself. If so, restarting the instance of the Database Engine corrects the problem. To continue working, you must reconnect to the instance of the Database Engine; otherwise, use DBCC to repair the problem. In some cases, you may have to restore the database. 5. 24: Indicates a media failure. The system administrator may have to restore the database. You may also have to call your hardware vendor. 2.4 Installation 1. Download SQL Server official link.
  • 36. 36 CHAPTER 2. SQL SERVER & SQL SERVER MANAGEMENT STUDIO 2. Open the software by double-clicking on it. Select Basic from the provided options. 3. Select Accept.
  • 37. 2.4. INSTALLATION 37 4. Press Install. 5. Wait for the installation to Complete.
  • 38. 38 CHAPTER 2. SQL SERVER & SQL SERVER MANAGEMENT STUDIO 6. Press the Customization Button from options. 7. Press Next till reach you reach “Feature Selection”
  • 39. 2.4. INSTALLATION 39 8. Check Database Engine Services 9. Now Press Next till reach you reach “Database Engine Configuration”, Click “Add Current User”, and Press Next.
  • 40. 40 CHAPTER 2. SQL SERVER & SQL SERVER MANAGEMENT STUDIO 10. Press Install. Close the Window After Completion. 11. Now Click on ”Install SSMS”.
  • 41. 2.4. INSTALLATION 41 12. Download setup file. 13. Open the software by double-clicking on it. Press Install.
  • 42. 42 CHAPTER 2. SQL SERVER & SQL SERVER MANAGEMENT STUDIO 14. Press Close after completion. 2.5 Create New Login 1. Security - Login - New Login
  • 43. 2.5. CREATE NEW LOGIN 43 2. Provide Unique Name - Select SQL Authentication - Check only Enforce a password policy 3. From Select a Page go to Server Roles - Check public and sysadmin
  • 44. 44 CHAPTER 2. SQL SERVER & SQL SERVER MANAGEMENT STUDIO 4. From Select a Page go to User Mapping - Select Database for the New Login
  • 45. Chapter 3 Transact-SQL Statements (Basic) 3.1 Load Data-set on SQL Server Management Studio 1. Open SSMS from the start menu 45
  • 46. 46 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 2. Connect to Server. 3. Right-click on Databases from Object Explorer, Click on new Database
  • 47. 3.1. LOAD DATA-SET ON SQL SERVER MANAGEMENT STUDIO 47 4. Type name & Press OK 5. Now Right click on the newly named database, Select Tasks then Import Flat File
  • 48. 48 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 6. Press Next, and provide the file path in the first textbox then press next. 7. In modify columns tab change nvarchar(50) to varchar(max) for each column, Press Next and Finish
  • 49. 3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 49 8. Wait for Results to compile, press close 3.2 DML (Data Manipulation Language) Statements 1. Right Click on the newly created Database and select New Query
  • 50. 50 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 2. Display Whole Table 3. Display Few Columns
  • 51. 3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 51 4. Display Distinct Values in one column 5. Display Count of Distinct Values for a column
  • 52. 52 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 6. Display rows having Same Value (String) 7. Display rows having the Same Value (Number)
  • 53. 3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 53 8. Display rows having Greater Value 9. Display rows having Less Value
  • 54. 54 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 10. Display rows having Greater/Equal Value 11. Display rows having Less/Equal Value
  • 55. 3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 55 12. Display rows having not same Value 13. Display rows having Range Values
  • 56. 56 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 14. Display rows having the same character at Start in Value 15. Display rows having the same character at End in Value
  • 57. 3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 57 16. Display rows having the same character at Any Position in Value 17. Display rows having the same character at the Second Position in Value
  • 58. 58 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 18. Display rows having the same character at Start with at least 6 characters in Value 19. Display rows having different characters at Start in Value
  • 59. 3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 59 20. Display rows having the same character range at Start in Value 21. Display rows having the same multiple characters at Start in Value
  • 60. 60 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 22. Display rows having the same character at the Start and end in Value 23. Display rows having Value in specified Strings
  • 61. 3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 61 24. Display rows having Multiple conditions True 25. Display rows having At-least one condition True
  • 62. 62 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 26. Display rows having No Condition True 27. Display rows having Null Value
  • 63. 3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 63 28. Display rows having No Null Value 29. Display Sorted rows using one column
  • 64. 64 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 30. Display Sorted rows using one column (Decreasing) 31. Display Sorted rows using Multiple columns
  • 65. 3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 65 32. Display Top n Values 33. Display Top n Percent Values
  • 66. 66 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 34. Display Top n Values (using Where) 35. Display Minimum Values of a Column
  • 67. 3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 67 36. Display Maximum Values of a Column 37. Display Average of a Column
  • 68. 68 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 38. Display Sum of a Column 39. Display same column with a new name
  • 69. 3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 69 40. Display Column Values in groups 41. Display rows having specified values
  • 70. 70 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 42. Create Tags for each group values 43. Insert Columns in New Tables
  • 71. 3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 71 44. Insert values in the row 45. Update Values
  • 72. 72 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 46. Update Values (Multiple) 47. Delete Values
  • 73. 3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 73 48. Display rows on one table by using a second table (exists) 49. Display rows on one table by using a second table (Any)
  • 74. 74 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 50. Display rows on one table by using a second table (ALL) 51. Join Two Tables using Inner Join
  • 75. 3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 75 52. Join Two Tables using Left Join 53. Join Two Tables using Right Join
  • 76. 76 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 54. Join Two Tables using Outer Join 55. Take Union of Two Tables
  • 77. 3.2. DML (DATA MANIPULATION LANGUAGE) STATEMENTS 77 56. Take Intersection of Two Tables 57. Replace Null Values (Temporary)
  • 78. 78 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 3.3 Data Definition Language (DDL) 3.3.1 Procedure/Variables for Existing Database 1. Create a Procedure 2. Execute Procedure
  • 79. 3.3. DATA DEFINITION LANGUAGE (DDL) 79 3. Create a variable and use it in Query 3.3.2 Database 1. Create Database
  • 80. 80 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 2. For Backup Permission in C Drive, Select SQL Server 2019 Configuration Manager 3. Open SQL Server and select local System in Build-in Account
  • 81. 3.3. DATA DEFINITION LANGUAGE (DDL) 81 4. Backup Database 5. Backup Database (Only Changes)
  • 82. 82 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 6. Delete Database 7. Restore Database
  • 83. 3.3. DATA DEFINITION LANGUAGE (DDL) 83 3.3.3 Table 1. Create Table 2. Delete Table
  • 84. 84 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 3. Truncate Table 4. Add new column to a Table
  • 85. 3.3. DATA DEFINITION LANGUAGE (DDL) 85 3.3.4 Column 1. Change column properties 2. Delete column
  • 86. 86 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 3. Change Property of a column (null) 4. Change Property of a column (not null)
  • 87. 3.3. DATA DEFINITION LANGUAGE (DDL) 87 5. Change Property of a column (Unique) 6. Change Property of a column (primary)
  • 88. 88 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC) 7. Change Property of a column (Check) 8. Change Property of a column (Default)
  • 89. 3.3. DATA DEFINITION LANGUAGE (DDL) 89 9. Run Serial in one column
  • 90. 90 CHAPTER 3. TRANSACT-SQL STATEMENTS (BASIC)
  • 91. Chapter 4 School Management System 4.1 ER-Diagram 91
  • 92. 92 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM 4.2 Database Development 1. Create Database named School Management System 2. Create Table named Attendance • Attendance ID (PK, int, not null, auto-increment) • Class (varchar(20)) • Session (varchar(10)) • Section (varchar(10)) • Subject Code (FK, varchar(20)) • Staff ID (varchar(15)) • Attendance Date (datetime) • Admission Number (FK, varchar(15)) • Status (varchar(10))
  • 93. 4.2. DATABASE DEVELOPMENT 93 3. Create Table named Book • Accession Number (PK, varchar(30), not null) • Book Title (varchar(30)) • Author (varchar(30)) • Joint Authors (varchar(30)) • Subject (varchar(30)) • Department (varchar(30)) • Barcode (varchar(70)) • ISBN (varchar(30)) • Volume (varchar(30)) • Edition (varchar(30)) • Publisher (varchar(30)) • Place of Publisher (varchar(30)) • CD (varchar(10)) • Publishing Year (int) • Reference (varchar(10)) • Almira Position (varchar(30)) • Price (int) • Supplier Name (varchar(30)) • Bill Date (datetime) • Remarks (varchar(max))
  • 94. 94 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM 4. Create Table named Book Issue Staff • Transaction ID (PK, varchar(15), not null) • Issue Date (datetime) • Due Date (datetime) • Accession No (varchar(30)) • Staff ID (varchar(15)) • Status (varchar(30)) 5. Create Table named Book Return Student • Return ID (PK, varchar(15), not null) • Transaction ID (varchar(15)) • Return Date (datetime)
  • 95. 4.2. DATABASE DEVELOPMENT 95 • Fine (int) 6. Create Table named Bus Holders • Admission Number (varchar(15)) • Source Location (varchar(250)) • Starting Date (date) 7. Create Table named Class • ID (PK, int, not null) • Class Name (varchar(20)) • Section (varchar(20))
  • 96. 96 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM 8. Create Table named Course Fee • ID (PK, int, not null) • Class ID (int) • Fee ID (int) • Fee (float) • Month (varchar(30)) 9. Create Table named Department • ID (PK, int, not null) • Department Name (varchar(250), not null)
  • 97. 4.2. DATABASE DEVELOPMENT 97 10. Create Table named Employee • Staff ID (PK, varchar(50), not null) • Staff Name (varchar(30)) • Father Name (varchar(30)) • Mother Name (varchar(30)) • Date of Birth (date) • Permanent Address (varchar(100)) • Temporary Address (varchar(100)) • Phone Number (varchar(11)) • Mobile Number (varchar(11)) • Date of Joining (date) • Qualification (varchar(70)) • Years of Experience (float) • Designation (varchar(100)) • Email (varchar(30)) • Picture (image) • Status (varchar(15)) • Basic Salary (int) • Department (varchar(100)) • Gender (varchar(10))
  • 98. 98 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM 11. Create Table named Event • Event ID (PK, int, not null) • Event Name (varchar(150)) • Starting Date and Time (datetime) • Ending Date and Time (datetime) • Managed By (varchar(250)) • Activities (varchar(max)) 12. Create Table named Examination • ID (PK, int, not null) • Examination Name (varchar(30)) • Examination Type (varchar(30))
  • 99. 4.2. DATABASE DEVELOPMENT 99 13. Create Table named Fee • ID (PK, int, not null) • Fee Name (varchar(50)) 14. Create Table named Grades • Grade ID (PK, int, not null) • Grade (varchar(50)) • Score From (float) • Score To (float) • Remark (varchar(max)) • Grade Points (float)
  • 100. 100 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM 15. Create Table named Hostel Fee Payment • Hostel Fee Payment ID (PK, varchar(15), not null) • Admission Number (varchar(15)) • Total Paid (int) • Mode of Payment (varchar(50)) • Payment Mode details (varchar(200)) • Fine (int) • Due Fees (int) • Date and Time of Payment (datetime) • Hostel Fees (int) 16. Create Table named Hostel Information
  • 101. 4.2. DATABASE DEVELOPMENT 101 • ID (PK, int, not null) • Hostel Name (varchar(150), not null) • Hostel Address (varchar(150), not null) • Managed By (varchar(100)) • Hostel Phone Number (varchar(11), not null) • Hostel Mobile Number (varchar(11)) • Hostel Fees (int) 17. Create Table named Marks Entry • Marks Entry ID (PK, int, not null) • Admission Number (varchar(15)) • Student School (varchar(250)) • Session (varchar(100)) • Student Class (varchar(150)) • Student Section (varchar(100)) • Entry Date (datetime) • Result (varchar(20))
  • 102. 102 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM 18. Create Table named Scholarship • Scholarship ID (PK, int, not null) • Scholarship Name (varchar(30)) • Description (varchar(max)) • Amount (int) 19. Create Table named School • School ID (PK, int, not null) • School Name (varchar(250)) • Address (varchar(250)) • Contact Number (varchar(11)) • Email (varchar(30))
  • 103. 4.2. DATABASE DEVELOPMENT 103 • Website (varchar(60)) 20. Create Table named Student • Admission Number (PK, varchar(15), not null) • Enrollment Number (varchar(15)) • Student Name (varchar(100)) • Father Name (varchar(100)) • Mother Name (varchar(100)) • Father Contact Number (varchar(11)) • Permanent Address (varchar(250)) • Temporary Address (varchar(250)) • Student Contact Number (varchar(11)) • Email ID (varchar(60)) • Date of Birth (date) • Gender (varchar(10)) • Admission Date (date) • Session (varchar(15)) • Caste (varchar(15)) • Religion (varchar(15)) • Photo (image) • Status(varchar(15)) • Nationality (varchar(50)) • Class (varchar(20)) • Section (varchar(30)) • School ID (int)
  • 104. 104 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM 21. Create Table named Subject • Subject Code (PK, varchar(20), not null) • Subject Name (varchar(250)) • Class Name (varchar(20)) 22. Create Table named Supplier • ID (PK, varchar(15), not null) • Supplier Name (varchar(30)) • Address (varchar(200)) • Contact No (varchar(15))
  • 105. 4.2. DATABASE DEVELOPMENT 105 • Email ID (varchar(50)) 23. Create Table named Transportation • Route ID (PK, int, not null) • Source Location (varchar(250)) • Bus Charges (int) 24. Add Foreign Key Constraints to following Columns • Attendance (Subject Code) with Subject (Subject Code) • Attendance (Admission Number) with Student (Admission Number) • Book Issue Staff (Accession Number) with Book (Accession Number) • Book Issue Staff (Staff ID) with Employee (Staff ID) • Bus Holder (Admission Number) with Student (Admission Number)
  • 106. 106 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM • Course Fee (Class ID) with Class (ID) • Course Fee (Fee ID) with Fee (ID) • Hostel Fee Payment (Admission Number) with Student (Admission Number) • Student (School ID) with School (school ID) 4.3 User Interface 1. Connect Database to your Visual Studio
  • 107. 4.3. USER INTERFACE 107 2. Login Page using System; using System.Data.SqlClient; using System.Windows.Forms; namespace SchoolManagementSystem { public partial class Login : Form { private string role; private string connectString = "Data Source=(LocalDB)MSSQLLocalDB;AttachDb" + "Filename=|DataDirectory|SchoolManagementSystem.mdf;Integrated Securit" + "y=True"; public Login() => InitializeComponent(); public string Role { get => role; set => role = value; } public string setrole() { if (radioButtonAdmin.Checked == true) Role = "admin"; else if (radioButtonParent.Checked == true) Role = "parent"; else if (radioButtonStudent.Checked == true) Role = "student"; else if (radioButtonTeacher.Checked == true) Role = "teacher"; else Role = " "; return Role; } private void ButtonLogin_Click(object sender, EventArgs e) { SqlConnection sqlcon = new SqlConnection(); sqlcon.ConnectionString = connectString; sqlcon.Open();
  • 108. 108 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM string username = textBoxUsername.Text; string password = textBoxPassword.Text; string role = setrole(); string query = "select userName, passWord, role from login where userNam" + "e='" + textBoxUsername.Text + "'and passWord='" + textBoxPassword.Text + "'and role='" + role + "'"; SqlCommand cmd = new SqlCommand(query, sqlcon); SqlDataAdapter da = new SqlDataAdapter(cmd); if (da != null) { if (role == "admin") { Administrator adminForm = new Administrator(); adminForm.Visible = true; this.Hide(); } else if (role == "parent") { Parent parentForm = new Parent(); parentForm.Visible = true; this.Hide(); } else if (role == "teacher") { Teacher teacherForm = new Teacher(username); teacherForm.Visible = true; this.Hide(); } else if (role == "student") { Students studentForm = new Students(username); studentForm.Visible = true; this.Hide(); } } else { MessageBox.Show("Invalid Login please check username/password/role"); } } } }
  • 109. 4.3. USER INTERFACE 109 3. Admin Page • View Employee or Student Record using their IDs • Add or Delete Login Credentials • Add or Delete Employee Information
  • 110. 110 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM • Add or Delete Student Information • View, Add and Delete School Information • Add, View and Delete Hostel Information using System; using System.Data;
  • 111. 4.3. USER INTERFACE 111 using System.Data.SqlClient; using System.Drawing; using System.IO; using System.Windows.Forms; namespace SchoolManagementSystem { public partial class Administrator : Form { public string connection = "Data Source=(LocalDB)MSSQLLocalDB;AttachDbFil" + "ename=|DataDirectory|SchoolManagementSystem.mdf;Integrated Security=True"; public string query; public string imgLocation; SqlConnection sqlcon = new SqlConnection(); SqlDataReader reader; byte[] images = null; public void opensql() { sqlcon.ConnectionString = connection; sqlcon.Open(); } public void queryexecute() { SqlCommand cmd = new SqlCommand(query, sqlcon); cmd.Connection = sqlcon; cmd.CommandType = CommandType.Text; int a = cmd.ExecuteNonQuery(); if (a != -1) { MessageBox.Show("Successful"); } else { MessageBox.Show("Error"); } } public void queryexecutearray() { SqlCommand cmd = new SqlCommand(query, sqlcon); reader = cmd.ExecuteReader(); reader.Read(); } public String addpicture() { OpenFileDialog openFileDialog = new OpenFileDialog(); if (openFileDialog.ShowDialog() == DialogResult.OK) { imgLocation = openFileDialog.FileName.ToString(); return imgLocation; } return null; } public void addpictureinrecord() { FileStream stream = new FileStream(imgLocation, FileMode.Open, FileAccess.Read); BinaryReader brs = new BinaryReader(stream); images = brs.ReadBytes((int)stream.Length); } public Administrator()
  • 112. 112 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM { InitializeComponent(); } //Add New Login Details private void button2_Click(object sender, EventArgs e) { opensql(); query = "insert into login values ('" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')"; queryexecute(); sqlcon.Close(); } //Remove Old Login Detail private void button3_Click_1(object sender, EventArgs e) { opensql(); query = "delete from login where username = '" + textBox2.Text + "'"; queryexecute(); sqlcon.Close(); } //Update Login Details private void button17_Click(object sender, EventArgs e) { opensql(); if (String.IsNullOrEmpty(textBox2.Text)) { MessageBox.Show("Enter Username"); } else { if (String.IsNullOrEmpty(textBox4.Text)) { query = "update login set passWord = '" + textBox3.Text + "' where userName = '" + textBox2.Text + "'"; queryexecute(); } else if (String.IsNullOrEmpty(textBox3.Text)) { query = "update login set role = '" + textBox4.Text + "' where userName = '" + textBox2.Text + "'"; queryexecute(); } else { query = "update login set role = '" + textBox4.Text + "', passWord = '" + textBox3.Text + "' where " + "userName = '" + textBox2.Text + "'"; queryexecute(); } } sqlcon.Close(); } //View Login Details private void button16_Click(object sender, EventArgs e) { opensql(); query = "select * from login where userName = '" + textBox2.Text + "'"; queryexecutearray(); textBox3.Text = (String)reader[1];
  • 113. 4.3. USER INTERFACE 113 textBox4.Text = (String)reader[2]; sqlcon.Close(); } //View Employee or Student Information private void button1_Click(object sender, EventArgs e) { opensql(); if (radioButton1.Checked == true) query = "select *, convert(varchar(max), dateOfJoining), convert(var" + "char(max), dateOfBirth), convert(varchar(max), yearsOfExperienc" + "e), convert(varchar(max), basicSalary) from employee where staf" + "fID = '" + textBox1.Text + "'"; else if (radioButton2.Checked == true) query = "select *, convert(varchar(max),dateOfBirth), convert(varcha" + "r(max),admissionDate), convert(varchar(max),schoolID) from stud" + "ent where enrollmentNumber = '" + textBox1.Text + "'"; else MessageBox.Show("Select one of the above option"); queryexecutearray(); if (radioButton1.Checked == true) { label2.Text = "Staff ID: " + "n" + "Date of Joining: "+"n" + "Empl" + "oyee Name: " + "n" + "Father's Name: " + "n" + "Mother's Na" + "me: " + "n" + "Date of Birth: " + "n" + "Gender: " + "n" + "Parmenant Address: " + "n" + "Temporary Address: " + "n" + "Personal Number: " + "n" + "Professional Number: " + "n" + "" + "Qualification: " + "n" + "Expirence: " + "n" + "Designation: " + "" + "n" + "Email: " + "n" + "Status: " + "n" + "Salary: " + "n" + "Deparment: "; label3.Text = (string)reader[0] + "n" + (string)reader[19] + "n" + (string)reader[1] + "n" + (string)reader[2] + "n" + (string)reader[3] + "n" + (string)reader[20] + "n" + (string)reader[18] + "n" + (string)reader[5] + "n" + (string)reader[6] + "n" + (string)reader[8] + "n" + (string)reader[7] + "n" + (string)reader[10] + "n" + (string)reader[20] + "n" + (string)reader[12] + "n" + (string)reader[13] + "n" + (string)reader[15] + "n" + (string)reader[21] + "n" + (string)reader[17]; byte[] photo = (byte[])reader[14]; if (photo != null) { MemoryStream ms = new MemoryStream(photo); pictureBox2.Image = Image.FromStream(ms); } } else if (radioButton2.Checked == true) { label2.Text = "Admission Number: " + "n" + "Enrollment Number: " + "n" + "Student Name: " + "n" + "Father's Name: " + "n" + "Mot" + "her's Name: " + "n" + "Date of Birth: " + "n" + "Gender: " + "n" + "Parmenant Address: " + "n" + "Temporary Address: " + "n" + "Personal Number: " + "n" + "Father's Number: " + "n" + "Email ID: " + "n" + "Admission Date: " + "n" + "Session: " + "n" + "Caste: " + "n" + "Religion: " + "n" + "Status: " + "n" + "Nationality: " + "n" + "Class: " + "n" + "Section: " + "n" + "School ID: "; label3.Text = (string)reader[0] + "n" + (string)reader[1] + "n" + (string)reader[2] + "n" + (string)reader[3] + "n" + (string)reader[4] + "n" + (string)reader[22] + "n" + (string)reader[11] + "n" + (string)reader[6] + "n" +
  • 114. 114 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM (string)reader[7] + "n" + (string)reader[8] + "n" + (string)reader[5] + "n" + (string)reader[9] + "n" + (string)reader[23] + "n" + (string)reader[13] + "n" + (string)reader[14] + "n" + (string)reader[15] + "n" + (string)reader[17] + "n" + (string)reader[18] + "n" + (string)reader[19] + "n" + (string)reader[20] + "n" + (string)reader[24]; byte[] photo = (byte[])reader[16]; if (photo != null) { MemoryStream ms = new MemoryStream(photo); pictureBox2.Image = Image.FromStream(ms); } } label23.Text = "Photo"; sqlcon.Close(); } //Add Picture (Employee) private void button4_Click_1(object sender, EventArgs e) { pictureBox1.ImageLocation = addpicture(); } //Add Picture (Student) private void button9_Click(object sender, EventArgs e) { pictureBox3.ImageLocation = addpicture(); } //Add Employee Record private void button5_Click(object sender, EventArgs e) { addpictureinrecord(); opensql(); query = "insert into employee values ('" + textBox18.Text + "','" + textBox17.Text + "','" + textBox16.Text + "','" + textBox15.Text + "','" + textBox14.Text + "','" + textBox13.Text + "','" + textBox12.Text + "','" + textBox11.Text + "','" + textBox10.Text + "','" + textBox9.Text + "','" + textBox8.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox19.Text + "', @images,'" + textBox20.Text + "','" + textBox21.Text + "','" + textBox22.Text + "','" + textBox23.Text + "')"; queryexecute(); sqlcon.Close(); } //Delete Employee Record private void button6_Click(object sender, EventArgs e) { opensql(); query = "delete from employee where username = '" + textBox18.Text + "'"; queryexecute(); sqlcon.Close(); } //Add Student Information private void button8_Click(object sender, EventArgs e) { addpictureinrecord(); opensql(); query = "insert into student (admissionNumber, enrollmentNumber, " + "studentName, fatherName, motherName, fatherContactNumber, " + "permanentAddress, TemporaryAddress, studentContactNumber, emailID, " +
  • 115. 4.3. USER INTERFACE 115 "dateOfBirth, gender, admissionDate, session, caste, religion, status, " + "nationality, class, section, schoolID, photo) select '" + textBox24.Text + "','" + textBox25.Text + "','" + textBox26.Text + "','" + textBox27.Text + "','" + textBox28.Text + "','" + textBox29.Text + "','" + textBox30.Text + "', '" + textBox31.Text + "','" + textBox32.Text + "','" + textBox33.Text + "',convert(date,'" + textBox34.Text + "'),'" + textBox35.Text + "',convert(date,'" + textBox36.Text + "'), '" + textBox37.Text + "', '" + textBox38.Text + "', '" + textBox39.Text + "', '" + textBox40.Text + "', '" + textBox41.Text + "', '" + textBox42.Text + "', '" + textBox43.Text + "', '" + textBox44.Text + "', @images"; queryexecute(); sqlcon.Close(); } //Delete Student Information private void button7_Click(object sender, EventArgs e) { opensql(); query = "delete from student where admissionNumber = '" + textBox24.Text + "'"; queryexecute(); sqlcon.Close(); } //View School Details private void button11_Click(object sender, EventArgs e) { opensql(); query = "select * from school where schoolID = '" + textBox45.Text + "'"; queryexecutearray(); textBox46.Text = (String)reader[1]; textBox47.Text = (String)reader[2]; textBox48.Text = (String)reader[3]; textBox49.Text = (String)reader[4]; textBox50.Text = (String)reader[5]; sqlcon.Close(); } //Add School Details private void button10_Click(object sender, EventArgs e) { opensql(); query = "insert into school values ('" + textBox45.Text + "','" + textBox46.Text + "','" + textBox47.Text + "','" + textBox48.Text + "','" + textBox49.Text + "','" + textBox50.Text + "')"; queryexecute(); sqlcon.Close(); } //Remove School Details private void button12_Click(object sender, EventArgs e) { opensql(); query = "delete from school where schoolID = '" + textBox45.Text + "'"; queryexecute(); sqlcon.Close(); } //View Hostel Details private void button14_Click(object sender, EventArgs e) { opensql(); query = "select *, convert(varchar(max), hostelFees) from " +
  • 116. 116 CHAPTER 4. SCHOOL MANAGEMENT SYSTEM "hostelInformation where ID = '" + textBox56.Text + "'"; queryexecutearray(); textBox55.Text = (String)reader[1]; textBox54.Text = (String)reader[2]; textBox51.Text = (String)reader[3]; textBox57.Text = (String)reader[4]; textBox53.Text = (String)reader[5]; textBox52.Text = (String)reader[7]; sqlcon.Close(); } //Add Hostel Detail private void button15_Click(object sender, EventArgs e) { opensql(); query = "insert into hostelInformation values ('" + textBox56.Text + "','" + textBox55.Text + "','" + textBox54.Text + "','" + textBox51.Text + "','" + textBox57.Text + "','" + textBox53.Text + "'," + "'" + textBox52.Text + "')"; queryexecute(); sqlcon.Close(); } //Delete Hostel Details private void button13_Click(object sender, EventArgs e) { opensql(); query = "delete from hostelInformation where ID = '" + textBox56.Text + "'"; queryexecute(); sqlcon.Close(); } } }
  • 117. Chapter 5 Transact-SQL Statements (Intermediate) 5.1 Joins 1. Display Customers Details like Title, Full Name (First Name, Middle Name, Last Name, Suffix), Full Address (AddressLine1, AddressLine2, City, StateProvince, CountryRegion), Postal Code, and Phone No 117
  • 118. 118 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE) 2. Display Customer ID, Full Name, Product Name, Color and Unit Price 3. Display Product Name, Standard Cost, List Cost, Total Orders and Total Profit
  • 119. 5.1. JOINS 119 4. Display Combined List of First Name and Last Name with at least 3 characters 5. Display Product Name, Total Orders and State/Province from which Orders were Placed
  • 120. 120 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE) 6. Display Product Name, Category Name and Model Name 7. Display Product Name, Category Name, Model Name and Culture
  • 121. 5.1. JOINS 121 8. Display Parent Category and Child Category 9. Display Product Name and its Description
  • 122. 122 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE) 10. Display Company Name an Email Address where Freight rate is more than 1000 11. Calculate the Percentage of Subtotal and Tax amount
  • 123. 5.2. VARIABLES AND PROCEDURES 123 12. Display Customer ID, Full Name (Title, First Name, Middle Name, Last Name, Suffix), Company Name, Phone, Address Type, Full Address (AddressLine1, AddressLine2, City, State, Country, Postal Code), Subtotal, Tax Amount, Freight Rate, Total Cost 5.2 Variables and Procedures 1. Declare a variable with datatype int
  • 124. 124 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE) 2. Declare a variable with datatype varchar 3. Declare and Assign a value to a variable
  • 125. 5.2. VARIABLES AND PROCEDURES 125 4. Declare, Assign and Display the value of a variable 5. Using Variables Display Products in given Price Range
  • 126. 126 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE) 6. Using variables Display Count of Specific Color 7. Create Procedure having a variable for colour and Display its count
  • 127. 5.2. VARIABLES AND PROCEDURES 127 8. Create a Procedure that displays records for a given postal code 9. Create a Procedure that displays records for a given total profit
  • 128. 128 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE) 10. Create a Procedure that displays the record for a given Order Quantity or Product ID 11. Create a Procedure that displays a message of the total amount for a given Sales ID
  • 129. 5.3. SUB-QUERIES AND VIEWS 129 5.3 Sub-queries and Views 1. Display Specific Customer Details using sub-query 2. Display Product having maximum sales using sub-query
  • 130. 130 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE) 3. Display Customers from Canada using Sub-Query 4. Display Customers who paid more than 200 in Freight rate using Sub-Query
  • 131. 5.3. SUB-QUERIES AND VIEWS 131 5. Create View to display Customer First Name and Phone Number 6. Create View and Procedure to display Customer First Name and Phone Number where the First name is Dominic
  • 132. 132 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE) 7. Create View to display Product Sales report where the minimum sale is 30 8. Create View and insert data
  • 133. 5.3. SUB-QUERIES AND VIEWS 133 9. Create View to update values 10. Alter View, add checkpoint and try to update values Note: You can only insert or delete from a single table. If you make any changes to the base tables you can use the sp refreshview procedure to recompile the view.
  • 134. 134 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE) 5.4 Program Flow Statements 1. Return 2. Throw (Error Code, Message, State)
  • 135. 5.4. PROGRAM FLOW STATEMENTS 135 3. Try Catch 4. Waitfor (time)
  • 136. 136 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE) 5. Waitfor (delay) 6. While
  • 137. 5.4. PROGRAM FLOW STATEMENTS 137 7. Begin End 8. Break
  • 138. 138 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE) 9. Continue 10. If else
  • 139. 5.5. TRANSACTIONS 139 11. Goto 5.5 Transactions 1. Create a Transaction to delete the customer
  • 140. 140 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE) 2. Create a Transaction to insert the product details 3. Create a Transaction to update the product detail
  • 141. 5.5. TRANSACTIONS 141 4. Create a Transaction to delete the customer and commit it 5. Create a Transaction to insert the product details and rollback it
  • 142. 142 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE) 6. Create a Transaction to delete the customer and add save points to which we can rollback Note: To check the oldest active transaction use DBCC OPENTRAN 5.6 Triggers 1. Create insert Trigger for List Price
  • 143. 5.6. TRIGGERS 143 2. Create update Trigger for Modified Date 3. Create delete Trigger for Product ID
  • 144. 144 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE) 4. Create create Trigger for database 5. Create alter Trigger for database
  • 145. 5.6. TRIGGERS 145 6. Create drop Trigger for database Note: Trigger is a stored routine. it is a set of SQL statements used for protecting the integrity of data. But constraint is used to define rules to allow or restrict what values can be stored in columns. The purpose of inducing constraints is to enforce the integrity of the database. it restricts the insertion of data in a table. The trigger can be on update/delete statements also, but constraints are related to providing restrictions while inserting the data. All insert, update, and delete triggers can be found in respective trigger folders in Table details, whereas all create, drop, and alter triggers are stored in database triggers which can be found in the programmability folder of the respective database.
  • 146. 146 CHAPTER 5. TRANSACT-SQL STATEMENTS (INTERMEDIATE)
  • 147. Chapter 6 Malicious 6.1 Queries 1. Display all products excluding the top 10 products 147
  • 148. 148 CHAPTER 6. MALICIOUS 2. Display 20 products excluding the top 10 products 3. Display top 12 products including similar values
  • 149. 6.1. QUERIES 149 4. By using self-join display Category and sub-category 5. Display list using cross join
  • 150. 150 CHAPTER 6. MALICIOUS 6. Display Products using the correlated query 7. Create Order Detail Summary using cube
  • 151. 6.1. QUERIES 151 8. Create Order Detail Summary using rollup 1 9. Display newly inserted record on the screen 1Note: The difference between cube and rollup is that cube generates all possible combinations for the given attributes whereas rollup only generates hierarchical combinations
  • 152. 152 CHAPTER 6. MALICIOUS 10. insert multiple records at once 11. Copy only table structure
  • 153. 6.1. QUERIES 153 12. Copy only the top 10 percent sold products to the new table 13. Show count of customers in the state vs country
  • 154. 154 CHAPTER 6. MALICIOUS 14. Create Schema for your database 15. Create a new table in the schema
  • 155. 6.1. QUERIES 155 16. Add a new computed column to your table 17. Create a local temporary table
  • 156. 156 CHAPTER 6. MALICIOUS 18. Create a global temporary table 19. Create a Synonym for the table
  • 157. 6.2. CREATE SETUP FILE 157 20. Set a column to generate Globally unique identifier 21. Change the order of forms in Visual Studio (a) Double Click file named Programs.cs (b) Change form1 to your desired form class in ”Application.Run(new form1());” 6.2 Create Setup File (a) Go to Extensions, select Manage Extensions, search setup and download Microsoft Visual Studio Installer Project
  • 158. 158 CHAPTER 6. MALICIOUS (b) Close Visual Studio, Click on Modify and wait for the setup to complete (c) Reopen your Visual Studio Project, Right Click on Solution and select Add New Project
  • 159. 6.2. CREATE SETUP FILE 159 (d) Select Setup Project and name it. (e) Right Click on Application Folder, and Select Project Output
  • 160. 160 CHAPTER 6. MALICIOUS (f) Click OK (g) Right Click on Application Folder and Add your database files
  • 161. 6.2. CREATE SETUP FILE 161 (h) Select User’s Desktop, Right click on the window, select Application folder and primary output file and rename it (i) Select User’s Program Menu, Create a new folder, Create Shortcut and rename it
  • 162. 162 CHAPTER 6. MALICIOUS (j) In Solution Explorer right click on the setup file, select properties, click on Prerequisites, select SQL Server 2019, and Click OK (k) Select database from Application Folder and change Property Permanent to True
  • 163. 6.2. CREATE SETUP FILE 163 (l) Click on Properties, select publish, click on prerequisite, select SQL Server 2019 (m) Click on the option and provide details and press OK, Now click on Publish and your setup is complete
  • 164. 164 CHAPTER 6. MALICIOUS
  • 165. Appendix A Lab Details Lab No Chapter 01 Visual Studio 02 SQL Server & SQL Server Management Studio 03 Transact-SQL Statements (Basic) 04 05 06 School Management System 07 08 Transact-SQL Statements (Intermediate) 09 10 11 12 13 14 Malicious 15 16 Students’ Questions 165