SQL Server Database Management Guide
SQL Server Database Management Guide
INTRODUCTION
Microsoft SQL Server is a DBMS developed and marketed by Microsoft.
It is software that allows for the storage of data in a coherent and organized manner.
to easily view and modify their content.
He uses TSQL (Transact SQL) for his queries: it is an implementation of
SQL that supports stored procedures as well as triggers. SQL Server
uses the TDS format (Tabular Data Stream or communication protocol between clients)
and the server)
The first version of SQL Server was released in 1986, today it is at version 19.
But in the context of this course, we will use SQL Server 2017 version 17.9.
I. OPERATION
There are 2 types of servers on which the SQL environment can be deployed:
The OLTP server (Online Transactional Processing) which is a transactional server.
that is to say a server on which a certain number of LMD type transactions
can be executed. Most of the time OLTP systems are used for the
entry of orders, financial transactions, customer relationship management
etc. these systems have a large number of users who make requests
short and returns relatively few records.
In summary, an OLTP server has the following characteristics:
Primary data files: which are mandatory and have the .mdf extension
contains the catalog of the database;
Secondary data files: optional and with .ndf extensions that contain the
objects and user data.
I noted well:
Each database contains a single primary data file.
2. CREATION OF A DATABASE
To create a database, one can either use TSQL or SSMS.
1. Use of SSMS
In the object explorer, connect to an instance of the database engine.
data;
Right-click on the database, then click on New database
data
In the new database, enter the name of your database;
-To create the database accepting all default values, click on
OK;
To modify the default values of primary files and log files,
this is done in the database file grid, click on the cell
appropriate, then enter the new value;
-To modify the database options, select the options tab, then
make the changes of your choice;
To add an extended property to the database, select property
extended
2. USE OF TSQL
In the standard toolbar, click on new query.
USE master;
GO
CREATE DATABASE GL
ON
(NAME = GL_dat,
DATABASE ADMINISTRATION
3. DELETE A DATABASE
a) Utilization of SSMS
In the object explorer, connect to an object instance of the database engine
of data;
- Developed the database file, right-click on the database
data to be deleted, then click on DELETE;
Check that the correct database is selected and then click OK.
Delete database
USE master;
GO
DROP DATABASE GL ;
GO
DATABASE ADMINISTRATION
4. RENAME A DATABASE
a) With SSMS
Always check that there are no open connections to the database; it is necessary
So define the database in single-user mode, in order to close all the
open connections and prevent other users from connecting during the
the name of the database has been changed.
To do this:
Right-click on the database to modify, then click on
PROPERTY;
In the properties dialog box, click on OPTION
In the option restrict access, select single user;
If other users are connected to the database, a message will open.
the connections appear to apply the property and close all the others
connexions, cliqué sur oui
In the object explorer developed based on a database, click with the button
right-click on the database to rename, then click rename.
Enter the name of the database and then click OK.
b) With TSQL
USE master;
GO
ALTER DATABASE GL SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
ALTER DATABASE GL MODIFY NAME=GLCOPY;
GO
ALTER DATABASE GLCOPY SET MULTI_USER;
GO
REAL
Date and Time
DATE
TIME
DATETIME
SMALL DATE TIME
DATE TIME 2
DATETIME OFFSET
The string type
CHAR
VARCHAR
TEXT
Unicode character strings
NVARCHAR
NCHAR
NTEXT
The binary chains
TYPE IMAGE
BINARY TYPE
TYPE VARBINARY
3. WITH TSQL
Use nom_bd;
GO
CREATE TABLE schema (DBO)
4. Delete a table
Vous ne pouvez pas supprimer une table ayant une contrainte, vous devez au préalable
remove the constraint. When a table is deleted, the rules and values associated with it are
associated ones are automatically deleted
DATABASE MANAGEMENT
The deletion of a table automatically leads to the deletion of all the relationships it has.
maintenance
UNDER SSMS
In the object explorer, expand the database node, select the database
of data, then the table node
Right-click on the table, then in the context menu click on
delete
A message asks you to confirm the deletion, click on OK.
5. RENAME A TABLE
a) UNDER SSMS
In the object explorer, right-click on the table to rename it.
Use GL ;
Go
Exec sp_rename '[Link]', 'cours';
Go
b) With TSQL
ALTER TABLE SCHEMA.TABLE_NAME ADD COLUMN_NAME TYPES1 ….
GO
7. DELETE A COLUMN
a) UNDER SSMS
- Search for the table where you want to remove the columns, expand it to
expose the names of the different columns
Right-click on the column to delete and then click on delete
In the dialog box to delete an object, click on ok
If the column contains constraints or other dependencies, a message will be displayed.
In the dialog box, delete an object. Resolve the error by deleting the
referenced constraints
You cannot delete a column that has a check constraint, you must
first remove the constraint
DATABASE ADMINISTRATION
b) TSQL
ALTER TABLE [Link]
DROP COLUMN COLUMN_NAME ;
DROP CONSTRAINT COLUMN_NAME;
GO
8. RENAME A COLUMN
a) SSMS
In the object explorer, right-click on the column to rename and
choose to rename
Enter a new column name and validate
b) TSQL
USE DATABASE_NAME;
GO
EXEC SP_RENAME
SCHEMA.TABLE_NAME.OLD_COLUMN_NAME
‘NOM_NOUVELLECOLONNE’, ‘COLUMN’ ;
9. INSERTING ROWS INTO A TABLE
10. Practical case
Create a database Gest_Etudiant with 3 extensions, a primary file, a
secondary and
DATABASE ADMINISTRATION
Database creation
USE master ;
GO
CREATE DATABASE GEST_ETUDIANT
ON
(NAME = STUDENT_DATA_dat,
FILENAME = "C:\Program Files\Microsoft SQL"
Server\[Link]\MSSQL\DATA\GEST_ETUDIANT.mdf
SIZE=10
MAXSIZE = 50,
FILEGROWTH = 5),
DATABASE ADMINISTRATION
SIZE=10
MAXSIZE = 50,
FILEGROWTH = 5)
LOG ON
(NAME = GEST_ETUDIANT_dat,
FILENAME = "C:\Program Files\Microsoft SQL"
Server\[Link]\MSSQL\DATA\GEST_ETUDIANT.ldf
SIZE = 5 ,
MAXSIZE = 25,
FILEGROWTH = 5);
GO
Continuation of the TD
USE STUDENT_DB;
GO
/* CREATION OF THE STUDENT TABLE IN DBO*/
date_naiss DATE,
sect VARCHAR(20) NULL,
age INT
);
DATABASE ADMINISTRATION
);
);
GO
WHERE
[Link].code_mat = 12518;
DATABASE ADMINISTRATION
Go
Select * from [Link] where Name like '%[O]%'
Go
Name of the student with the highest grade?
When faced with a request, one must ask oneself what am I supposed to
make and what tables to use?
Use Student Management
Go
Select Top(1)* from [Link] e
Inner join note n on([Link]-Etud=n.num_Etud)
order by [Link] DESC;
go
or well
select name from [Link] e inner join [Link] n on (e.student_number = n.student_number)
Use Student_Management
Go
Select section, count (*) as student_count from [Link]
Group by ([Link]);
Go
Go
Select count (*) as Nes_en_1988 from [Link] where year(date_naiss)=1988;
Go
Display the average of each student
Use Student_Management
Go
Select name, isnull(note*coef/sum(coef),0) as average from [Link] e
Left join [Link] n on(e.student_number = n.student_number)
where nom_directeur='HInaud';
go
display the list of directors,
for each sector manager the number of departments they oversee
SELECT chef_secteu, COUNT(*) AS number_of_departments
from [Link]
group by ([Link].head_sector);
go
[Link].num_dir = [Link].num_direct
inner join [Link]
on [Link].code_dep = [Link].code_dep
where
[Link].section_head='FISHER';
go
go
go
Go
Go
Select director_name from [Link] where age > (select AVG(age) from director);
Go
Nb structure of
Select_field,function
From dbo.nom_table
Clause (Where
Order by
Group by
Having
Condition
Go
7) Delete a table
A - under SSMS
- In the object explorer, expand the database node, then select the database.
data then the node table
- Right-click on the table and then click on delete in the context menu.
- A message will ask you to confirm the deletion, click OK.
b- On TSQL
Request:
Go
DATABASE ADMINISTRATION
Go
Rename a table
a. With SSMS
- Right-click on the table to rename
- Then enter a new name in the column and validate.
b. With TSQL
Use Database_Name
go
a) With SSMS
- In the object explorer, expand the database node, select the database
give then click on the table on which you want to add columns
- Right-click on new columns, enter the new columns with their types.
and validate
b) With TSQL
a) UNDER SSMS
- Search the table from which you want to remove the columns, expand it to expose
the names of the different columns
- Right-click on the column to be deleted and then choose delete.
- In the dialog box, click on OK
- If the content column of the constraints or other dependencies has an error message
You will be displayed in the dialog box to delete an object. Resolve the error by deleting
the referenced constraints
Note: You cannot delete a column with a check constraint; you must first...
remove the constraint
b) UNDER TSQL
A) With SSMS
- In the object explorer, right-click on the column to rename and
choose to rename
- Enter a new name in the column and then confirm
B) WITH TSQL
- You do
USE database_name
- Accept input parameters and return multiple values in the form of parameters.
of sorting to the calling program
- Contain programming instructions that perform operations that perform
operations in the database
the first character of the name of local temporary procedures is a #. These procedures are
available only during the user's connection and are deleted as soon as the connection
is closed.
On the other hand, the OMS of the global temporary procedures starts with ##. These procedures are visible.
to all users and are deleted at the end of the last session using the procedure
They are included in SQL Server and are physically stored in the database.
resource data but logically appear in the SYS schema defined either by
system either by the user. The MSBD database also contains the procedures.
to enable the system in the dbo schema used to plan alerts
NB:
- Given that the stored procedures start with the prefix sp_, it is
It is recommended not to use this prefix when naming your procedures given
- If a user creates a stored procedure with the same name as a system procedure, this
the procedure will never be executed
- The programming of a stored procedure differs depending on whether this procedure does not receive any
parameter, receives input parameters, returns output parameters or returns
a value
c. Create a Stored Procedure
- Under SSMS
Database developer
Parameter Values
Author Your name
Date of Creation Today's date
Description Data that returns what your Procedure does
Click OK and then in the query editor write your query. Then to test the syntax
in the menu query click on analyze. If an error sms is returned compare the
instructions with the proposed instructions and make the necessary corrections
To execute the procedure, right-click on the name of the procedure and select.
execute the stored procedure by entering the corresponding parameters.
- With TSQL
Create PROCEDURE [schema]. procedure_name
@param1 type
@param n type n
As
SET NOCOUNT ON;
// instruction TSQL
Go
Exo
Stored procedure that displays the class and level of the student based on the procedure
As
GO
Declaration of a variable
OU
Allocation of information
PRINT(……)
If condition
BEGIN
// instruction
END
ELSE
BEGIN
DATABASE ADMINISTRATION
// instruction
END
Display an error when the user enters a name that is not in the database.
Use Gest_etud
@penom varchar(25)
AS
BEGIN
From [Link]
Where Prenom=@prenom,
END
Else
Begin
END
Go
I want to check if a student has a grade in SQL Server. If so, we display it.
student's grade if not we display 'the student does not have a grade'
Correction
Go
AS
SET NOCOUNT ON
Display the list of students (first name and last name with an additional gender column that
display masculine, feminine according to the student's gender
FROM [Link]
GO
EXO
Display the list of students and indicate in each type column whether they are
MINOR or MAJOR
Use
Go
DATABASE MANAGEMENT
As
CASE
WHEN (year (getdate ()) - year (date_naiss) < 18) THEN 'MINOR'
END
From [Link]
Go
Transaction management
A transaction allows for the execution of a group of instructions, if for any reason
if one of these instructions was not executed, the entire instruction group is canceled:
To declare a transaction, the BEGIN TRAN statement is used.
To validate the transaction and make the associated processes effective, we
use the COMMIT TRAN instruction.
To interrupt a transaction that has not yet been validated, one uses
the instruction ROLLBACK TRAN
Syntax:
BEGIN TRANSACTION
//Instruction.
COMMIT TRAN
Example:
BEGIN TRAN exple
Delete from order where numCom=5
Delete from orderLine where orderNum=5
COMMIT TRAN
DATABASE ADMINISTRATION
When an error is encountered, the database engine associates a message with it. If
The error does not exist in the [Link] table of the master database, it receives the code
50000. The engine also adds a notion of severity (degree of seriousness of an error),
which is rated by a value:
From 0 to 9: this means that the information messages indicate errors that
are not very serious (warnings).
Severity 10: The information messages report minor errors, and the
convert a gravity of 10 into gravity 0.
Gravity 11: Indicates that the object or entity does not exist.
Severity 12: Used for requests that do not have a lock.
Severity 13: Indicates blocking errors related to transactions.
Severity 14: Indicates errors related to security, such as a denied authorization.
Severity 15: Indicates syntax errors.
Severity 16: Indicates general errors.
From 17 to 19: Indicates software errors that cannot be corrected by
the user.
From 20 to 24: Indicates a system failure, and fatal errors that can occur
damage the BD.
Using RAISERROR :f
These are parameters used for substituting the variables defined in the
message.
With OPTION: It is a customized option for the error.
La gestion des curseurs.