ADMINISTERING DATABASES ON SQL SERVER Level 32024
ADMINISTERING DATABASES ON SQL SERVER Level 32024
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
Course outline
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.
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.
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
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.
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).
Lab:
2- Creation of a database.
To create a database, you can either use SQL Server Management Studio or use SQL Transact.
In the Value column, enter the text for the extended property; then click OK
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
3- Delete a database
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.
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
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.
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');
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.
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.
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.
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.
Nom_colonneN typeN;
GO
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.
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
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
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.
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.
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
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
Devoir : Displays the list of students and indicates for each student in the Type column whether they
are minor or major.
FROM dbo.students
GO
exec dbo.agetest
go
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
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.
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.
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.
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.
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.
UNION ALL
UNION ALL
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.