0% found this document useful (0 votes)
30 views33 pages

ADMINISTERING DATABASES ON SQL SERVER Level 32024

Uploaded by

billnelson651
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views33 pages

ADMINISTERING DATABASES ON SQL SERVER Level 32024

Uploaded by

billnelson651
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

ADMINISTERING DATABASES ON SQL SERVER 1

AFRICAN INSTITUTE OF COMPUTER


SCIENCES (AICS) BP:13719
TEL: (+237) 242 72 99 57 / 242 72 99 58

WEB: www.iaicameroun.com
E-MAIL: [email protected]

ADMINISTERING
DATABASES ON SQL
SERVER

Mr. MESSIO
Computer Engineer / Teacher in IAI
Cameroon

Email: [email protected]
Tel: (+237) 699349176

ADMINISTERING DATABASES ON SQL SERVER Page 1


ADMINISTERING DATABASES ON SQL SERVER 2

Course outline

Part I : Introduction to SQL Server

Part II : Getting Started with SQL Server

Part III: Practical work

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


2
ADMINISTERING DATABASES ON SQL SERVER 3

Part I: Introduction to SQL SERVER

Introduction

Microsoft SQL Server is an RDBMS developed and marketed by Microsoft. SQL Server is a
software that allows data to be stored in a consistent and organized way so that it can easily view
and modify its content. It uses the T-SQL language (Transact-Sql) for its queries. It is an
implementation of SQL that supports stored procedures as well as triggers. It is originally multi base
and multischema. For data transfer, SQL Server uses the TDS format: Tabular Data Stream (a
protocol that allows communication between clients and the server).
The 1st version of SQL SERVER was released in 1989. Today it is at version 19; and as part of this
course, we will use SQL Server 2017 version 17.9.

I. Operation
There are two types of servers on which the SQL Server environment can be deployed.

The OLTP server (Online Transactional Processing) which is a transactional


server, i.e. a server on which a number of DML transactions can be executed.
Sql server is for operationnal databases.
Most of the time OLTP systems are used for order entry, financial transactions, customer
relationship management and sales, these systems have a large number of users who make
short transactions and return relatively few records.
In summary, an OLTP server has the following characteristics:
- Transactions involve small amounts of data
- Has a large number of users
- Response times are quite fast
- Requires high availability

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


3
ADMINISTERING DATABASES ON SQL SERVER 4

The OLAP (Online Analytical Processing) server is a decision server. It allows to


consolidate the data coming from multiple sources thanks to an ETL (extraction transformation
loading which allows to extract the data coming from multiple sources: Excel, XML, and MySQL ...
transforms them into the same format and then loads them into a data warehouse).
OLAP performs a multidimensional analysis (e.g. a company can compare its computer sales in June
with its July sales and then compare them with the data stored in another database // compare and
analyze the data in a different way) of the company data and offers the possibility of performing
complex calculations. It is used in business for performance management, planning, forecasting,
financial reporting....It provides analysts and managers with the information they need to make
decisions.
In summary, an OLAP server allows:
- Fast data analysis
- Organize and compare data
- Optimize queries and reporting
- Perform complex calculations
- Manipulate a large amount of data (can go to several Terabytes = 10e12 bytes)

II. SQL Server Components


Microsoft SQL Server consists of several software programs that run as a service. Some have
graphical interfaces, others are accessible via a command line. SQL Server is composed of 05 main
services:

SQL SERVER: This is the Database Engine service (a central component of a dbms that
handles databases) and corresponds to a SQL Server instance (a set of memory zones and
background processes that provide access to a database). . It can help to do replication
concerning many sql servers to help to choose datas that we want to transit from one server to
another. This component runs as a Windows service and is referenced as MSSQLSERVER
for the default instance and MSSQLSERVER$instancename for a named instance. The name
of an instance is set during installation.

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


4
ADMINISTERING DATABASES ON SQL SERVER 5

SQL Server Integration Service (SSIS): This is the SQL Server tool for Import/Export,
Data Transfer, and data Transformation. It includes wizards for creating ETL (Extraction
Transformation Loading).

SQL Server Analysis Service (SSAS): This is the ideal component for business
intelligence projects. This component is an OLAP analysis and Data Mining tool from
Microsoft and allows you to build OLAP cubes (multidimensional database: rolap, molap,
holap with the particularity that molap is faster and more efficient than rolap but limited in
size (gigabytes)).

SQL Server Reporting Service (SSRS): It is thanks to this component that we can render
our data from our data warehouse in the form of reports (table, graph etc ....).

SQL Agent: In charge of SQL Server monitoring, this component also manages the
execution of scheduled tasks and the tracking of alerts. It is directly linked to a SQL Server
instance. It is referenced by default in Windows Service Manager as SQL Server Agent and
by SQL Server Agent (instance name) in the case of a named instance.

Service broker pour un échange de donnée entre différents serveurs. C’est de l’architecture
orientée service qui permet d’échanger des données sous forme de xml entre ces services.

III- Tools
The different tools that can be found in SQL Server are:
- SQL Server Management Studio (SSMS): It allows you to perform all operations at the
BD engine level.
- SQL Server Configuration Manager: This is used to manage all services related to SQL
Server.
- SQL Server Profiler: Use to track and analyze the workload of a SQL Server instance.
- Azure Data Studio: Formerly known as SQL Operations Studio, allows you to create
databases, query them, perform backups, restore databases

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


5
ADMINISTERING DATABASES ON SQL SERVER 6

- The SQL CMD: it allows to execute queries, scripts of commands.


- SQL SERVER DISTRIBUTED REPLAY: Helps you assess the impact of future SQL
SERVER upgrades. It is also used to assess the impact of hardware and operating system
upgrades.

IV- TASKS OF A SQL SERVER DATABASE


ADMINISTRATOR:

A SQL SERVER database administrator must be able to:

Install, configure the server, and administrate the databases


Manage physical storage space
Ensure the integrity of the data stored in the databases
set up backup plans
Implement solutions to maintain production continuity
Ensure data access performance is maintained
Participate in technology watch (always keep abreast of innovations in the sector)

V- Structure of an SQL Server DB


An SQL Server DB consists of two types of files, namely data files and log files.
Data files: there are two types: primary data files (mandatory and .mdf extension) that
contain the catalog of the database (centralized location where the information on the data
contained in a dB is grouped: we still speak of metadata// allows to better understand a data
//which make it possible to characterize the information of a dB ex: date of creation ...),
Each dB includes a primary data file. Secondary data files (optional and with an .ndf
extension) that contain user objects and data.
Log files: with the extension. ldf, they save all the changes of the database. They contain
the information that will be used for the restoration of the database. Each dB must have at
least one log file.

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


6
ADMINISTERING DATABASES ON SQL SERVER 7

VI- System objects


SQL server, like all relational database engines, has system objects: System databases and system
views
1-System databases
There are 4 different system databases:
- master (main database, it includes system tables)
- model (skeleton database that will be taken over each time we create a new database, so if we
have a particular option that we want our newly created databases to take we modify the model in
property—option)
- msdb (database that contains all the information of the tools that revolve around SQL Server... for
example when we make a backup there is a table that contains the history of backups we have made
on the databases or when we use the SQL agent that allows us to schedule system maintenance
work)
- tempdb (is a temporary database. Example: CREATE TABLE #t1 sample database).

2-System views
A view is a request that is stored in the server. When we create a complex query we create a view
and when we call the view the query behind it will be executed. All system objects are views
because it allows you not to modify the contents of the system tables. SQL server knows that there
is a client table because it maintains its own information, structure in system tables.
Example
SELECT * FROM sys.tables (sys is the schema or container for system objects) displays all tables in
a database with all its properties. It is therefore a view on the system tables that contains the
structures or metadata. So if I type SELECT * FROM sys.dm_exec_sessions this query will give me
the list of sessions that are currently running in sql server.
Or SELECT * FROM information_schema.tables.

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


7
ADMINISTERING DATABASES ON SQL SERVER 8

VII- SQL SERVER DATABASES


Let us create a database named facturation. After creating a database two files appear. A data
file(.mdf) and a transaction log file(.ldf) while specifying the size of our database. But if the size is
too small SQL Server can increase it automatically (Auto Growth). It is important to predefine the
file size because SQL SERVER will manage files on the disk within which it makes its own
allocation (its own move and layout) in order to optimize access and storage.
The database must be created in transact-sql with the command

CREATE DATABASE [SE3]


ON PRIMARY
( NAME = N'SE3', // with a logical file name
FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL15.SQLEXPRESS\MSSQL\DATA\SE3.mdf',// for
the file location
SIZE = 102400KB , // the file size is specified
FILEGROWTH = 65536KB ) // and automatic growth specification
LOG ON
( NAME = N'SE3_log',
FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL15.SQLEXPRESS\MSSQL\DATA\SE3_log.ldf' ,
SIZE = 51200KB ,
FILEGROWTH = 65536KB )
GO

NB: Size and specification are default values that do not necessarily need to be set because SQL
server takes values from a system database that is considered the skeleton of new databases created
(model).

You can even just specify nothing and just write


CREATE DATABASE name_database
GO //to define a group or script batch
Because the RDBMS will take default values into account and who will create files with the
default size of the models in the default directory of the data

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


8
ADMINISTERING DATABASES ON SQL SERVER 9

Part II: GETTING STARTED WITH SQL SERVER

Lab:

Install SQL SERVER 2019 DEVELOPER

1- Connect to an instance of SQL Server

Start SQL Server Management Studio


In the Server Type topic, select Database Engine.
for the server name, enter the name of your SQL instance
In the Authentication section, select Windows Authentication.
Click Connect.

2- Creation of a database.

To create a database, you can either use SQL Server Management Studio or use SQL Transact.

a. Using SQL Server Management Studio(SSMS)

In Object Explorer, connect to an instance of the SQL Server Data Engine.


Right-click Database, and then click New Database.
In New Database, enter the name of the database.
To create the database, accepting all default values, click OK.
To change the default values for primary files and log or transaction files, this is
done in the Database File grid, click the appropriate cell, and then enter the new
value.
To change the database options, select the Options tab, and then make the changes
that you want.
To add an extended property (custom properties) to the database, select Extended
Property.
In the Name column, enter the name of the extended property;

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


9
ADMINISTERING DATABASES ON SQL SERVER 10

In the Value column, enter the text for the extended property; then click OK

B. Using Transact SQL


On the Standard toolbar, click New Query:

USE master; (contains all the system information related to a SQL server system, it
records the existence of all databases and the location of their files, SQL server
cannot start if the database master is not available)
GO
CREATE DATABASE SE3
ON PRIMARY
(NAME=’SE3’,
FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL19.
MSSQLSERVER\MSSQL\DATA\SE3.mdf',
SIZE=10,
MAXSIZE=50,
FILEGROWTH=5)
LOG ON
(NAME=SE3_log,
FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL19.
MSSQLSERVER\MSSQL\DATA\SE3_log.ldf',
SIZE=5,
MAXSIZE=25,
FILEGROWTH=5); qte of space added to the file each time a new space is required
.it must be less than or equal to maxsize
GO

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


10
ADMINISTERING DATABASES ON SQL SERVER 11

3- Delete a database

a. Using SQL Server Management Studio (SSMS)

In Object Explorer, connect to an instance of objects in the Database Engine.


Expand the Database folder, right-click the database that you want to delete, and then click
Delete.
Verify that the correct database is selected and then click OK.

b. Using Transact SQL


USE master;
GO
DROP DATABASE SE3;
GO

4- Rename a database

a. With SSMS

Always check that there are no open connections to the database, so you must set the database to
single-user mode, to close all open connections and prevent other users from connecting, while
the name of the DB is changed. To do this:
Right-click the DB that you want to modify, and then click Properties.
In the Database Properties dialog box, click Options.
In the Restrict Access option, select Single User.
If other users are connected to the database, an Open Connections message appears
to apply the property and close all other connections; click YES.
In Object Explorer, expand the Database node, right-click the DB that you want to rename, and
then click Rename.
Enter the new database name, and then click OK.

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


11
ADMINISTERING DATABASES ON SQL SERVER 12

b. With T-SQL
The syntax is:

USE master;
GO
ALTER DATABASE SE3 SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
ALTER DATABASE SE3 MODIFY NAME=se3;
GO
ALTER DATABASE se3 SET MULTI_USER;
GO

5- Delete data or log files

a. With SSMS

 Expand the Database folder, right-click the DB on which you want to delete the file, and
then click Properties.
 Select File.
 In the Database File grid, select the file that you want to delete, and then click OK.

b. With Transact SQL


The syntax is:

USE master;
GO
ALTER DATABASE REMOVE FILE SE3_LOG ;
GO
To create a secondary file you are supposed to precise the name and location: this is the query

alter database SE3 add file (name=N'ss', filename= N'C:\Program Files\Microsoft SQL
Server\MSSQL15.SQLEXPRESS\MSSQL\DATA\ss.ndf');

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


12
ADMINISTERING DATABASES ON SQL SERVER 13

6- Creating a table

a. With SSMS

In Object Explorer, expand the Database node, and then select the database that will
contain the new table.
Right-click the Table node of your DB. Then click New Table.
Type the names of the columns, choose the data type, and specify whether null values are
allowed for each column.
To specify property benefits for a column, click the column and choose the appropriate
properties from the column's properties tab.
To specify a column as the primary key, right-click the column and select Set Primary
Key.
To create foreign key relationships, validation constraints, or indexes, right-click in the
Table Designer pane and select an object from the list.
By default, the table is contained in the BOD schema. To specify a different schema for the
table, right-click in the Table Designer pane, and select Properties. From the Schema
drop-down list, select the appropriate schema.
From the File menu, choose Save Table Name.
In the dialog box, choose a name for the table and click OK.

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


13
ADMINISTERING DATABASES ON SQL SERVER 14

b. With Transact SQL


The syntax is:
USE se3;
GO
CREATE TABLE dbo. Students (//schema: set of objects of the database like tables, views,
triggers, stored procedures: dbo means Database owner
studentID INT NOT NULL PRIMARY KEY IDENTITY,
courseID INT NOT NULL,
name NVARCHAR (50) NOT NULL,
first name NVARCHAR (50),
pseudo NVARCHAR (50) NOT NULL UNIQUE,
FOREIGN KEY(courseID) REFERENCES Courses(coursesID)
);
GO

TO describe a table in SSMS exec sp_column ‘dbo.tablename’


OR exec sp_help ‘dbo.tablename’
c. Data Types in SQL Server

 Exact numeric values: BIGINT, NUMERIC, BIG, SMALLINT, DECIMAL,


SMALLMONEY, INT, TINYINT, MONEY;
 Approximate numerical values: FLOAT, REAL;
 Date and time: DATE, TIME, DATETIME2 (year, month, day, hour, second, fraction of a
second), DATETIMEOFFSET (year, month, day, hour, second, fraction of a second, time
zone), DATETIME (year, month, day), SMALLDATETIME (seconds are zero);
 Character strings: CHAR, VARCHAR, TEXT;
 Unicode character strings (represents all language-specific characters): NCHAR,
NVARCHAR, NTEXT;
 Binary strings: IMAGE, VARBINARY (files, image.), BINARY.

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


14
ADMINISTERING DATABASES ON SQL SERVER 15

7- Delete a table
NB :
You cannot delete a table that is referenced by a FOREIGN KEY constraint, you must first
delete the constraint or the table that references it.
When a table is deleted, the rules and default values are deleted and all constraints associated
with it are automatically removed.
Deleting a table automatically removes all the relationships it has

a. Under SSMS
In Object Explorer, expand the Database node, and then select the database and then select the
Table node;
Right-click the table, and then on the shortcut menu, click Delete.
A message asks you to confirm the deletion, click OK.

b. Under Transact SQL


The syntax is:
USE se3;
GO
DROP TABLE dbo. Students;

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


15
ADMINISTERING DATABASES ON SQL SERVER 16

8- Rename a table

a. Under SSMS

In Object Explorer, right-click the table you want to rename to and choose Rename.
Enter a new name at the table and validate.

b. Under Transact SQL


The syntax is:
USE se3;
GO
EXEC sp_rename 'Students', 'newName'; (no need to put dbo on the new one
otherwise it will do it 2 times)
GO

9- Add columns to a table

a. Under SSMS

In Object Explorer, expand the Database node, select the database, and then click
the table on which you want to add columns;
Right-click the Column topic, and then click New Column.
Enter the new columns with their type and then validate.

b. Under Transact SQL


The syntax is:
USE se3;
GO
ALTER TABLE dbo.students ADD
Nom_colonne1 type1,
Nom_colonne2 type2,
...

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


16
ADMINISTERING DATABASES ON SQL SERVER 17

Nom_colonneN typeN;
GO

10- Delete a column


a. Under SSMS
Find the table you want to delete the columns, expand it to expose the names of the
different columns;
Right-click the column that you want to delete, and then choose Delete.
In the Delete Object dialog box, click OK;
If the column contains constraints or other dependencies, an error message will be
displayed in the Delete Object dialog box. Resolve the error by removing the
referenced constraints.
NB :
You cannot delete a column that has a CHECK constraint. You must first remove the
constraint
You cannot delete a column with PRIMARY KEY or FOREIGN KEY constraints or other
dependencies unless you use the table designer, otherwise you must first remove all
dependencies from the column.

b. Under Transact SQL


Syntax:
USE se3;
GO
ALTER TABLE dbo.Students
DROP COLUMN name;

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


17
ADMINISTERING DATABASES ON SQL SERVER 18

11- Rename a //column to check


a. Under SSMS
In object explorer, right-click the column you want to rename to and choose
Rename.
Enter a new name in the column and validate.

b. Under Transact SQL


USE se3;
GO
EXEC SP_RENAME 'dbo. students.Name', 'new_name_of_the _column4=';
GO

12- Insert rows into the table


INSERT INTO dbo. students (studentID, name, first name, track, level)
VALUES (1, N'ASANE', N'Derrick', N'Software Engineering', 3);

To insert rows with identity constraint, we are supposed to change the identity parameters by using
the query SET IDENTITY_INSERT table_name ON; for you to insert the id you want and you set it
OFF when you’re done and you want the auto-increment to continue.

13- Query the table and display the results


SELECT * FROM dbo.student

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


18
ADMINISTERING DATABASES ON SQL SERVER 19

14- Create or Change the database Schema


a. Under SSMS
In object explorer, expand your database folder, expand the database in which you want to
create the new database schema, right-click on the security folder and point to NEW and select
Schema..
Enter a new name of the schema on the new dialog box, the schema owner (it must be a
database user of the system or a role) alternately click search to open the search roles and users
dialog box and validate on ok

b. Under Transact SQL


USE [Database_name]
GO
CREATE SCHEMA [schema_name] AUTHORIZATION [username]
GO
Or simplely CREATE SCHEMA [schema_name];
GO // if you have the user authorisation already

You can also while creating a schema grant privileges at the same moment to a user thanos to access
your schema and deny for another one Avenger
Example
CREATE SCHEMA ully AUTHORIZATION guest
CREATE TABLE test(id int ,name nvarchar(15))
GRANT SELECT ON SCHEMA :: ully TO thanos
DENY SELECT ON SCHEMA::ully TO Avenger;
GO
To view the schemas in the database type SELECT * FROM sys.schemas;
You can transfer the ownership,of a table by using the query
ALTER SCHEMA iai TRANFER ully.test;
GO
ALTER SCHEMA iai TRANFER OBJECT :: ully.test;
GO

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


19
ADMINISTERING DATABASES ON SQL SERVER 20

15- Create a login and create a user with privileges


a. Under SSMS
In object explorer, expand your database folder, expand the database in which you want to
create the new database schema, right-click on the security folder and point to NEW and select
Schema..
Enter a new name of the schema on the new dialog box, the schema owner (it must be a
database user of the system or a role) alternately click search to open the search roles and users
dialog box and validate on ok

b. Under Transact SQL


USE [master]
GO
CREATE LOGIN [loginName] WITH PASSWORD=N'passw0rd' MUST_CHANGE,
DEFAULT_DATABASE= [master], CHECK_EXPIRATION=ON, CHECK_POLICY=ON
GO
USE [DatabaseName]
GO
CREATE USER [username] FOR LOGIN [loginName] WITH
DEFAULT_SCHEMA=[schemaName]
GO

16-Stored procedures
A stored procedure in SQL Server is a group of one or more T-SQL statements for easy use. The
procedures resemble constructs of other programming languages because they can:
Accept input parameters and return multiple values as output parameters to the calling
program;
Contain programming statements that perform operations in the database.
Stored procedures have the following advantages:
They ensure faster response time and better system performance;
They avoid rewriting the same instructions several times;
It is possible to give users the right to execute a stored procedure without having the

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


20
ADMINISTERING DATABASES ON SQL SERVER 21

right to the objects it handles.

a. Types of stored procedures


 User-defined: A user-defined procedure can be created in a user-defined database or any
other system database, except for the resource named DB.
 Temporary procedures: These are a form of user-defined procedure. There are two types:
local temporary procedures and global temporary procedures, which differ in name,
visibility and availability. The first character in the name of local temporary procedures is a
single #. These procedures are visible only at the user's current login and are deleted as soon
as the connection is closed.
However, the name of the global temporary procedures begins with double ##. These
procedures are visible to any user after they are created and are deleted at the end of the last
session that uses the procedure.
 System procedures: These are included in SQL Server and are physically stored in the
resource database, but they appear logically in the sys schema of each system- and user-
defined database. The msdb database also contains the system stored procedures in the dbo
schema, which are used to schedule alerts.

NB:
Because system stored procedures begin with the prefix sp_ it is recommended that you do
not use this prefix when naming your procedures;
If a user creates a stored procedure with the same name as a system stored procedure, that
procedure will never run;
Programming a stored procedure differs depending on whether the procedure receives no
parameters, receives input parameters, returns output parameters, or returns a value.

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


21
ADMINISTERING DATABASES ON SQL SERVER 22

b. Create a stored procedure


 Under SSMS:
To create a procedure in object explorer:
i. Log in to an instance of the DB engine and expand there.
Ii. Expand Database, select your database and then click Programmabilitate.
Iii. Right-click Stored Procedures, and then click on New Stored Procedure.
Iv. On the Query menu, click Specify Model Parameter Values.
v. In the dialog box, specify the values of the model parameters. Enter the following values:
Parameters Securities
Author Your name
Creation date Today's date
Description Data that returns what your procedure does
Procedure_name Stored procedure name
@param1 @nomduparametre
@datatype_form_param1 Type of parameter 1
Default_Value_form_param1 Valeur par défaut du paramètre 1
@param2 @nomduparametre2
Default_Value_form_param2 Valeur par défaut du parametre 2
@datatype_form_param2 Type du paramètre 2

vi. Click OK.


vii. In the query editor, write your query;

viii. To test the syntax on the Query menu, click Analyze. If an error message is returned,
compare the instructions with the information provided and make the necessary
corrections.
ix. To run the procedure on the Query menu, click Run.
x. To run the procedure, right click the procedure name and select Run stored Procedure. And
finally enter the corresponding parameters.

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


22
ADMINISTERING DATABASES ON SQL SERVER 23

 Use T-SQL :
Syntaxe
CREATE PROCEDURE schema.procedurename
@param1 type,
@param2 type
AS
SET NOCOUNT ON; // Prevents the display of the number of lines affected by the instruction dc
thus reducing the response time on the traffic
//instructions
GO
Exemple: create a stored procedure that takes a student’s first name as input and displays their last
name
CREATE PROCEDURE dbo.affichenom
@firsname nvarchar (20)
AS
SET NOCOUNT ON;
SELECT name FROM DBO.ETUDIANT WHERE firstname = @firstname
GO

Devoir :
1. Stored procedure that displays the number of students enrolled
2. Stored procedure that takes a student’s number as a parameter and then displays his class and
level

• Execution of a procedure
Exec procedurename ;
Declaring a variable
Declare @variablename type

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


23
ADMINISTERING DATABASES ON SQL SERVER 24

Assigning a value to a variable


Select @variablename = value ou Set @variablename = value.
Displaying information
Print ‘element to display’ ;
Use of alternative structures
If …else
If condition
Begin
//instructions
End
Else
Begin
//instructions
End
Example: How to display an error message to the user if the first name is not in the database
CREATE PROCEDURE dbo. afficheprenomavecerreur
@surname nvarchar (20)
AS
SET NOCOUNT ON;
DECLARE @prenom1 nvarchar (20);
SET @prenom1 = (SELECT surname FROM dbo. Etudiants WHERE surname=@surname)
IF @prenom1 is null
BEGIN
PRINT ‘l’étudiant n’existe pas’
END
ELSE
BEGIN
SELECT name,age FROM dbo. students WHERE surname = @surname
END
GO

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


24
ADMINISTERING DATABASES ON SQL SERVER 25

EXEC dbo. afficheprenomavecerreur @surname='ully';

Devoir :
We want to check if the Assoumou student has a grade in SQL SERVER if this is not the case
display: the Assoumou student does not have a grade.

Case
Case
When condition1 Then resultat1
….
When condition n Then resultat n
Else resultat n
End
Example : displays the list of students (last name and first names) with the addition of a gender
column that displays male, female or other according to their gender

CREATE PROCEDURE dbo. Affichegenre


AS
SET NOCOUNT ON;
SELECT name, surname, 'gender'=
CASE
WHEN sexe = 'M' THEN 'MALE'
WHEN sexe = 'F' THEN 'FEMALE'
ELSE 'OTHERS'
END
FROM dbo.students
GO

Devoir : Displays the list of students and indicates for each student in the Type column whether they
are minor or major.

create PROCEDURE dbo.agetest


AS
SET NOCOUNT ON;
SELECT name, surname, 'type'=
CASE
WHEN age < 20 THEN 'minor'
WHEN age >= 20 THEN 'major'
ELSE 'OTHERS'
END

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


25
ADMINISTERING DATABASES ON SQL SERVER 26

FROM dbo.students
GO

exec dbo.agetest
go

Utilisation des structures répétitives


WHILE condition
BEGIN
//instruction
END
Exemple As long as the average age of directors is less than 30 years, increase by one year all
directors who are below average age and then post each time the new list of directors.

WHILE ((SELECT AVG(age) FROM dbo. directeur) < 30)


BEGIN
UPDATE dbo. directeur
SET age = age + 1
WHERE (age < (SELECT AVG(age) FROM dbo. directeur)
SELECT * FROM dbo. directeur
END

Transaction management
• Transaction management
A transaction is used to execute a group of statements, if for some reason one of these statements
has not been executed, the entire group of statements is canceled
To start a transaction we use the BEGIN TRAN statement
• To validate the transaction, and make the processes associated with it effective,
use the COMMIT TRAN statement
To stop a transaction in progress that has not yet been committed, use the

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


26
ADMINISTERING DATABASES ON SQL SERVER 27

ROLLBACK TRAN statement


 SAVEPOINT is a point in a transaction where you can restore the
transaction to a certain point without canceling the entire transaction.

SYNTAXE of a transaction

To start
BEGIN TRAN nom_transaction
//instructions
COMMIT TRAN

To rollback
BEGIN TRAN nom_transaction
//instructions
ROLLBACK TRAN (but you cannot rollback if you have already commited)

To save
SAVE TRANSACTION savepoint_name
This command is only used to create a SAVEPOINT among the transactional statements.
The ROLLBACK command is used to roll back a group of transactions.

Here is the syntax to return to a SAVEPOINT.


ROLLBACK TRAN savepoint_name

In the following example, we will delete three different records from the Talents table. We
will need to create a SAVEPOINT before each deletion, so that we can ROLLBACK to any
SAVEPOINT at any time to return the appropriate data to its original state.

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


27
ADMINISTERING DATABASES ON SQL SERVER 28

Error message handling


For each error encountered, the engine associates it with the associated message. If the
error encountered during execution does not exist in the Sys table. messages from the
Master database it gets the code 50000.
The engine also adds a notion of severity (degree of severity of an error) which is denoted by a value:
Severity Description
0-9 Informational messages report errors that are not
very serious
10 Informational messages report minor errors, the
Database Engine converts severity 10 to severity 0
11-16 Indicates errors that can be corrected by the user

11 Indicates that the given object or entity does not


exist
12 Used for queries that do not use locks

13 Indicates transaction blocking errors

14 Indicates security-related errors, such as


permission denied
15 Indicates syntax errors

16 Indicates general errors

17-19 Indicates software errors that cannot be corrected


by the user
17 Indicates that the statement caused a SQL
server resource overload
18 Indicates a problem in the Database Engine
software, but the statement execution is complete
and the connection to the Database Engine
instance is retained. The system administrator
must be notified whenever a severity 18 message
is issued
19 Indicates that an unconfigurable limit of the

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


28
ADMINISTERING DATABASES ON SQL SERVER 29

Database Engine has been exceeded and that the


current batch process has been stopped
20-24 Indicates system problems and fatal errors that
can corrupt the database
20 Indicates that a statement encountered a problem

21 Indicates that a problem has been encountered and


affects all database tasks
22 Indicates that the table or index specified in the
message has been corrupted by a hardware or
software problem
23 Indicates that the integrity of the database is in
question because of a hardware or software
problem
24 Indicates a system failure. The system
administrator will then have to restore the
database

The Raiseerror statement displays a system error message


Syntax
Raiseerror(nummessage|message,severity,state,parameters)
Nummessage: Specifies the number of the message to call a message that is already available in the
sys table. Messages
Message: Your message to display
Severity: Represents the level of severity. Only the system administrator can add messages with a
severity level between 19 and 25
Status: A value between 1 and 127 that identifies the source from which the error was emitted
Parameters : parmetrics used to override variables defined in the message, these parameters can only
be int, varchar, binary, or varbinary

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


29
ADMINISTERING DATABASES ON SQL SERVER 30

15. THE VIEWS

Scripts to manage SQL Server views: Create, call, modify, or delete views.

Views are a powerful tool for structuring and displaying data, but how do you manage SQL Server
views with scripts? Created here with Transact-SQL scripts, they offer a number of advantages. For
example, views can be used to abstract data from an MS SQL database. In other words, creating
different views allows you to display different sets of data without changing the structure of the
underlying tables.

Views can be created read-only and updated, and they can also be used to filter or aggregate data in
a database. Views are useful for creating aggregated single-level reports. For example, to see the
total revenue of all customers or the total orders of a company's customers.

1. 1. Defining SQL Server Views

In Structured Query Language (SQL), a view is an object that allows you to select a set of data. This
set comes from other tables or views, which are themselves table-based. Selection is made on
columns and rows. This means that it is possible to: Filter rows vertically with a WHERE clause And
choose the columns horizontally or generate them in the SELECT clause.

SQL views allow you to visualize some or all of the data contained in tables without directly accessing the
content and structure of the table. They also allow you to aggregate data from multiple tables, selecting
columns with the same structures. The following are code examples for creating, editing, calling, or deleting
simple views or partitioned views.

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


30
ADMINISTERING DATABASES ON SQL SERVER 31

2. Create the source table for the views


All of the sample scripts below are based on this sales table:
CREATE TABLE [dbo].[VENTES]
(
[MoisNom] NVARCHAR(50), -- alphanumérique
[MoisCourant] BIT, -- booléen, 0 ou 1 , false / true
[NumeroMois] TINYINT, -- très petit entier, de 0 à 255
[NumeroEmploye] SMALLINT, -- petit entier, minimum -2^15, maximum 2^15
[NombreClients] INTEGER, -- entier, minimum -2^31, maximum 2^31
[NombreVentes] BIGINT, -- grand entier, minimum: -2^63, maximum 2^63
[Montant_HT] NUMERIC(15,5), -- numérique, 15 chiffres, dont 5 après la virgule
[Montant_TTC] DECIMAL(15,5) -- décimal, 15 chiffres, dont 5 après la virgule
);

3. Create a SQL Server view in T-SQL


First, here's an example of a T-SQL script to create a simple view based on the sales table whose
code is available above. So here's how to create a SQL Server view with a script to aggregate and
display the monthly sales for all the customer data in the table along with the sales made.

CREATE VIEW [dbo].[V_VENTES]


AS
SELECT
[NombreClients],
[NombreVentes],
[Montant_HT],
[Montant_TTC]
FROM [dbo].[VENTES];

4. Edit a view with T-SQL code

Second, use this code example to modify a view with the ALTER VIEW command. Here's an
example of T-SQL code for modifying a view. Verify the existence of the view beforehand to avoid
errors when executing SQL code in SSMS.

ALTER VIEW [dbo].[V_VENTES_E]


WITH ENCRYPTION
AS
SELECT
[NombreVentes], -- Suppression de la colonne [NombreClients]
[Montant_HT],
[Montant_TTC]
FROM [dbo].[VENTES];

Edit a SQL Server View (Alter View)

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


31
ADMINISTERING DATABASES ON SQL SERVER 32

5. Delete a SQL Server view


However, to completely delete a view then use the DROP VIEW command. This is because if the
view does not exist, then the error Unable to find object because it does not exist is displayed in the
Database Management System (DBMS)
.DROP VIEW [dbo].[V_VENTES];

6. Test if a SQL view exists to delete it without error


Indeed, it is advisable to do tests to avoid errors during the deletion of objects. To test the existence
of views, use the IF EXISTS command and then the DROP command.
IF EXISTS (
SELECT 1 FROM sys.objects
WHERE object_id = object_id(N'[dbo].[V_VENTES]')
AND type in (N'V') )
BEGIN
DROP VIEW [dbo].[V_VENTES];
END;

7. Create a partitioned view with UNION ALL


Similarly, to group data from multiple tables into a single partitioned view, use this example.
Basically, with a simple select query combined with a data union. Note that the three selections on
the tables (or views) must have the same structure.

CREATE VIEW [dbo].[V_VENTES_P]


AS
SELECT [NombreClients], [NombreVentes], [Montant_HT], [Montant_TTC]
FROM [dbo].[VENTES_01]

UNION ALL

SELECT [NombreClients], [NombreVentes], [Montant_HT], [Montant_TTC]


FROM [dbo].[VENTES_02]

UNION ALL

SELECT [NombreClients], [NombreVentes], [Montant_HT], [Montant_TTC]


FROM [dbo].[VENTES_03];

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


32
ADMINISTERING DATABASES ON SQL SERVER 33

8. Create a SQL View with the Encryption Option

Thus, encrypting a view simply hides the view's code in the sys.comments system table. In this case,
if the system uses Microsoft SQL replication, it does not publish the view.
The encryption option does not hide the data.

CREATE VIEW [dbo].[V_VENTES_E]


WITH ENCRYPTION
AS
SELECT
[NombreClients],
[NombreVentes],
[Montant_HT],
[Montant_TTC]
FROM [dbo].[VENTES];

MR. MESSIO, Master In MSI, Computer Engineer /Teacher in IAI Cameroon


33

You might also like