Uploaded by blakmtlkat

CS362IP03

advertisement
Structured Query Language (SQL)
for Data Management
Ben Williams
Individual Project I
CS362-1603A-05
07/19/16
Page 1
Introduction
This paper is in-progress. It is being built over the course of five weeks. For this project,
I used Microsoft SQL Server 2014. While I had the option of using 2016, it is still a fairly
new addition to the program and might still be buggy. That fact alone, accompanied by
the facts that A) I had MANY problems installing the former, and B) that my professor
is using latter, I should probably follow his lead. While I am no expert at code, I gave
this assignment my best effort and I hope it goes to show that even a normal guy like
me can use structured query language.
Table of Contents
Individual Project I – Creating and Managing Servers via
Microsoft SQL Server.........................................................................................pg3
Individual Project II - Security and Data Manipulation
Language (DML): Insert, Update and Delete……………………………...pg10
Individual Project III – Select Statements and Queries…………………...pg16
Individual Project IV…………………………………………………………pg23
Individual Project V………………………………………………………….pg24
Page 2
Individual Project
I – Creating and Managing Servers via Microsoft SQL Server
Microsoft has developed a wonderful product to manage servers via Structured
Query Language (SQL) called “SQL Server”. SQL Server has many subsets of programs
within itself, and this paper will focus mainly on using SQL Server Management Studio,
where the bulk of SQL occurs. When first launched, it needs to connect to what is
referred to as a database instance – in plain English, a set of memory structures that
manage database files. Once we are connected to the local computer or database, we
will build our database by right clicking on the Databases folder and click New
Database.
Once our database is created, we need to start adding our tables and putting our
information in. While we start doing this, the database will begin to auto-grow –
meaning the more information is added to the database, the more space the database
will take up on the hard drive it is installed on.
Page 3
To create our tables, we right click on the “Tables” folder within our new
database and hit “Table”. For this particular assignment, our tables are titled
“STUDENTS”, “ADVISORS”, “CLASSES” and “STUDENT_CLASSES”. We will be
starting with our advisors table.
Once the new table is added, we add in our column names and set our data
types. We will also select which row is the primary key and set our identity to “yes” by
double clicking “(Is Identity)”. We do this because this is identifying information we are
asking for the database to query.
Once all of our tables have been constructed with our primary keys set and our
identifying specification set to “YES” on all of our primary keys, we can begin to build
the database entity relationship diagram (ERD). To do this, we expand the Database
Diagrams folder, right click it, and select “New Database Diagram.” When the dialogue
window comes up, we highlight all of our tables and hit the “Add” button. The end
result is as follows.
Page 4
Once that has been built, we need to draw in our relationship models and
show our SQL scripts
Here is the script of the database.
Page 5
USE [master]
GO
/****** Object: Database [Class of 2016 Student Information]
Script Date: 7/11/2016
7:53:40 PM ******/
CREATE DATABASE [Class of 2016 Student Information]
CONTAINMENT = NONE
ON PRIMARY
( NAME = N'Class of 2016 Student Information', FILENAME = N'C:\Program Files\Microsoft
SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA\Class of 2016 Student Information.mdf' , SIZE =
3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
LOG ON
( NAME = N'Class of 2016 Student Information_log', FILENAME = N'C:\Program
Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA\Class of 2016 Student
Information_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO
ALTER DATABASE [Class of 2016 Student Information] SET COMPATIBILITY_LEVEL = 120
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [Class of 2016 Student Information].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO
ALTER DATABASE [Class of 2016 Student Information] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [Class of 2016 Student Information] SET ANSI_NULLS OFF
GO
ALTER DATABASE [Class of 2016 Student Information] SET ANSI_PADDING OFF
GO
ALTER DATABASE [Class of 2016 Student Information] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [Class of 2016 Student Information] SET ARITHABORT OFF
GO
ALTER DATABASE [Class of 2016 Student Information] SET AUTO_CLOSE OFF
GO
ALTER DATABASE [Class of 2016 Student Information] SET AUTO_SHRINK OFF
GO
ALTER DATABASE [Class of 2016 Student Information] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [Class of 2016 Student Information] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [Class of 2016 Student Information] SET CURSOR_DEFAULT GLOBAL
GO
ALTER DATABASE [Class of 2016 Student Information] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [Class of 2016 Student Information] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [Class of 2016 Student Information] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [Class of 2016 Student Information] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [Class of 2016 Student Information] SET DISABLE_BROKER
GO
ALTER DATABASE [Class of 2016 Student Information] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [Class of 2016 Student Information] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [Class of 2016 Student Information] SET TRUSTWORTHY OFF
GO
Page 6
ALTER DATABASE [Class of 2016 Student Information] SET ALLOW_SNAPSHOT_ISOLATION OFF
GO
ALTER DATABASE [Class of 2016 Student Information] SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [Class of 2016 Student Information] SET READ_COMMITTED_SNAPSHOT OFF
GO
ALTER DATABASE [Class of 2016 Student Information] SET HONOR_BROKER_PRIORITY OFF
GO
ALTER DATABASE [Class of 2016 Student Information] SET RECOVERY SIMPLE
GO
ALTER DATABASE [Class of 2016 Student Information] SET MULTI_USER
GO
ALTER DATABASE [Class of 2016 Student Information] SET PAGE_VERIFY CHECKSUM
GO
ALTER DATABASE [Class of 2016 Student Information] SET DB_CHAINING OFF
GO
ALTER DATABASE [Class of 2016 Student Information] SET FILESTREAM( NON_TRANSACTED_ACCESS
= OFF )
GO
ALTER DATABASE [Class of 2016 Student Information] SET TARGET_RECOVERY_TIME = 0 SECONDS
GO
ALTER DATABASE [Class of 2016 Student Information] SET DELAYED_DURABILITY = DISABLED
GO
USE [Class of 2016 Student Information]
GO
/****** Object: Table [dbo].[Advisors]
Script Date: 7/11/2016 7:53:40 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Advisors](
[AdvisorID] [int] IDENTITY(1,1) NOT NULL,
[Fname] [nvarchar](50) NOT NULL,
[Lname] [nvarchar](50) NOT NULL,
[EmailAddr] [nvarchar](max) NOT NULL,
CONSTRAINT [PK_Advisors] PRIMARY KEY CLUSTERED
(
[AdvisorID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[Classes]
Script Date: 7/11/2016 7:53:40 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Classes](
[ClassID] [int] IDENTITY(1,1) NOT NULL,
[ClassCode] [varchar](50) NOT NULL,
[ClassName] [varchar](100) NOT NULL,
[Description] [varchar](max) NOT NULL,
CONSTRAINT [PK_Classes] PRIMARY KEY CLUSTERED
(
[ClassID] ASC
Page 7
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[Student_Classes]
Script Date: 7/11/2016 7:53:40 PM
******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Student_Classes](
[StudentClassID] [int] IDENTITY(1,1) NOT NULL,
[StudentID] [int] NULL,
[ClassID] [int] NULL,
[StartDate] [date] NULL,
[Assignment1] [int] NULL,
[Assignment2] [int] NULL,
[Assignment3] [int] NULL,
[Assignment4] [int] NULL,
[ClassGPA] [decimal](3, 2) NULL,
CONSTRAINT [PK_Student_Classes] PRIMARY KEY CLUSTERED
(
[StudentClassID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Students]
Script Date: 7/11/2016 7:53:40 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Students](
[StudentID] [int] IDENTITY(1,1) NOT NULL,
[FName] [nvarchar](50) NOT NULL,
[LName] [nvarchar](50) NOT NULL,
[Birthdate] [date] NOT NULL,
[Gender] [char](10) NOT NULL,
[StartDate] [date] NOT NULL,
[GPA] [decimal](18, 0) NOT NULL,
[IsActive] [bit] NOT NULL,
[Bio] [nvarchar](max) NULL,
[AdvisorID] [int] NOT NULL,
CONSTRAINT [PK_Students] PRIMARY KEY CLUSTERED
(
[StudentID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
Page 8
GO
ALTER TABLE [dbo].[Student_Classes] WITH CHECK ADD CONSTRAINT
[FK_Student_Classes_Classes] FOREIGN KEY([ClassID])
REFERENCES [dbo].[Classes] ([ClassID])
GO
ALTER TABLE [dbo].[Student_Classes] CHECK CONSTRAINT [FK_Student_Classes_Classes]
GO
ALTER TABLE [dbo].[Student_Classes] WITH CHECK ADD CONSTRAINT
[FK_Student_Classes_Students] FOREIGN KEY([StudentID])
REFERENCES [dbo].[Students] ([StudentID])
GO
ALTER TABLE [dbo].[Student_Classes] CHECK CONSTRAINT [FK_Student_Classes_Students]
GO
ALTER TABLE [dbo].[Students] WITH CHECK ADD CONSTRAINT [FK_Students_Advisors] FOREIGN
KEY([AdvisorID])
REFERENCES [dbo].[Advisors] ([AdvisorID])
GO
ALTER TABLE [dbo].[Students] CHECK CONSTRAINT [FK_Students_Advisors]
GO
USE [master]
GO
ALTER DATABASE [Class of 2016 Student Information] SET READ_WRITE
GO
And there you have it – our very own database with its ERD and SQL
scripts.
Page 9
Individual Project
II – Security and Data Manipulation Language (DML):
Insert, Update and Delete
In this chapter, we will be adding data into our tables for editing. I will first go
through adding all of the data into the database using Microsoft SQLServer
Management Studio, and then do some editing as well as some deletions as per the
instructions of this assignment. First of all, let’s begin by adding our data into the
database. We will first add in our Student Advisors into the database. Here is the
information that needs to be added:
Name
Fred Stone
Bob Gordon
Jack Simpson
E-mail
[email protected]
[email protected]
[email protected]
A few simple steps are all it takes to add data into the database. We begin by
selecting our database (in this case, ‘Class of 2016 Student Information’), then hitting
New Query at the top menu bar. Once open, we will expand our ‘Tables’ folder and
expand ‘dbo.Advisors’ and then ‘Columns’. Take note of our fields in here – we will
need them to write the SQL. In our New Query window, we will type the following:
select * from Advisors;
To execute a command, simply highlight and hit the ‘Execute’ button at the second bar
from the top. This will show all of the data that is currently in our table. In this case, it is
empty.
Page 10
To add data into the tables, use an Insert statement. We do not need to insert
data into the primary key fields; only the other information.
insert into Advisors(Fname,Lname,EmailAddr)
values('Fred', 'Stone', '[email protected]')
insert into Advisors(Fname,Lname,EmailAddr)
values('Bob', 'Gordon', '[email protected]')
insert into Advisors(Fname,Lname,EmailAddr)
values('Jack', 'Simpson', '[email protected]')
Once our data is added, we can move onto the next group of information. Let’s
continue our coding with the ‘Classes’ table.
select * from Classes;
insert into Classes(ClassCode,ClassName,[Description])
values ('ACCT306', 'Accounting 1', 'This course introduces accounting concepts and
explores the accounting environment. It covers the basic structure of accounting, how to
maintain accounts, use account balances to prepare financial statements, and complete the
accounting cycle. It also introduces the concept of internal control and how to account
for assets.')
Page 11
insert into Classes(ClassCode,ClassName,[Description])
values ('CS362', 'Structured Query Language for Data Management', 'This course gives
complete coverage of SQL, with an emphasis on storage, retrieval, and manipulation of
data.')
insert into Classes(ClassCode,ClassName,[Description])
values ('ENG115', 'English Composition', 'In this course, students focus on developing
writing skills through practice and revision. Students will examine expository, critical,
and persuasive essay techniques.')
insert into Classes(ClassCode,ClassName,[Description])
values ('FIN322', 'Investments', 'This course focuses on investments and investment
strategies. Various investment vehicles such as stocks, bonds, and commodities are
examined. Students will explore the principles of security analysis and valuation.')
Onto the ‘Students’ table….
select * from Students;
insert
values
'3')
insert
values
'1')
insert
values
'3')
insert
into Students(FName,LName,Birthdate,Gender,StartDate,GPA,IsActive,Bio,AdvisorID)
('Craig', 'Franklin', '1970-03-15', 'Male', '2010-05-30', '3.10', 'Yes', 'null',
into Students(FName,LName,Birthdate,Gender,StartDate,GPA,IsActive,Bio,AdvisorID)
('Harriet', 'Smith', '1982-04-15', 'Female', '2010-05-30', '3.22', 'Yes', 'null',
into Students(FName,LName,Birthdate,Gender,StartDate,GPA,IsActive,Bio,AdvisorID)
('George', 'David', '1984-11-05', 'Male', '2010-10-01', '0.00', 'Yes', 'null',
into Students(FName,LName,Birthdate,Gender,StartDate,GPA,IsActive,Bio,AdvisorID)
Page 12
values ('Ben', 'Jefferson', '1976-09-25', 'Male', '2009-02-21', '1.80', 'No', 'The
student has gone on temporary leave to pursue other opportunities but plans on returning
in 1 year.', '3')
Next, we need to show an example of a Delete statement. Delete statements can
be tricky. I actually just deleted some of my data when I failed to include a where clause
in my statement (OH S***!). A good practice in writing out delete statements is to write
a select statement first to show what you have in your table. Run your select statement
to select only the data you want deleted by using the primary key. In this case, the
primary key is 8 instead of 4 as I accidentally deleted all of my data and hadn’t taken
screenshots yet.
select * from Classes where ClassID=8
Page 13
As you can see, it only selected the Investments class, which is the class I need to delete
for this assignment. Now we will modify our Select statement into a Delete statement as
follows:
Page 14
Now we will modify Harriet Smith’s information as follows.
update Students set Birthdate='1982-04-25', GPA='3.25'
where StudentID=6
In short, this is how to insert, update and delete information in Microsoft SQL
Page 15
Individual Project
III – Select Statements and Queries
In this section of the project, we will begin writing select statements to meet the
requirements in our assignment. These select statements are similar to the ones we have
used in the last few assignments, except these will be more specific to acquire the data
that we want. Beforehand, we would use an asterisk [*] to select all of the data in a
specific table. These statements will require us to use the “where” clause quite often and
will vary in complexity depending on requirements. We will be doing many different
queries here, and I will separate them with the requirement listed in our assignment
instructions.
With our first select statement, we need to list all active male students assigned
to the advisors Fred Stone or Jack Simpson. We will open up a New Query window and
type the following select statement:
select FName, LName, AdvisorID from Students
where isactive='yes' and Gender='male'
Page 16
Next, we need to list all students that do not have a biography. We can use the
same statement as the one above, but swap out AdvisorID with Bio, and with our where
clause, type “ bio=’null’ “.
select FName, LName, Bio from Students
where Bio='null'
Now, we need to list all classes that are in the English department. We can use
the “like” statement to do this.
select * from Classes where ClassCode like 'E%'
Page 17
Now we need to create a list of all students with their listed advisors sorted by
the advisor’s name first followed then by the student’s name. We also must include the
student’s birth date, gender, and GPA. We will need to use a joined syntax command
“join”
select adv.Fname, adv.Lname, adv.AdvisorID, stud.Fname, stud.Lname, stud.Birthdate,
stud.Gender, stud.GPA
from Advisors adv inner join Students stud on adv.AdvisorID=stud.AdvisorID
order by adv.FName, adv.Lname, stud.Fname, stud.Lname desc
Page 18
We now need to list all students born in the 1980s.
select * from Students
where Birthdate like '198%'
Page 19
Now we need to display an average GPA for the genders. In order to get an
average from SQL, we need to use the aggregate statement (avg).
select stud.Fname, stud.Lname, stud.Gender, avg(GPA)
from Advisors adv inner join Students stud on adv.AdvisorID=stud.AdvisorID
group by stud.Fname, stud.Lname, stud.Gender
Page 20
Finally, the big one…. We must list all advisors and the number of active
students assigned to each and filter out any advisors with more than 1 student.
select adv.AdvisorID, adv.FName, adv.LName, count(stud.StudentID) as "Count(students)"
from Advisors adv
join students stud
on adv.AdvisorID=stud.AdvisorID
group by adv.AdvisorID, adv.Fname, adv.Lname
having count(stud.StudentID)='1';
Page 21
Page 22
Download
Random flashcards
State Flags

50 Cards Education

Countries of Europe

44 Cards Education

Art History

20 Cards StudyJedi

Sign language alphabet

26 Cards StudyJedi

Create flashcards