0% found this document useful (0 votes)
28 views

1.4 MS SQL Server (Database and Schema) - Section - 2

This document provides an introduction and overview of SQL and database concepts. It discusses what SQL is, why it is used, different SQL data types, how to log into SQL Server Management Studio, create databases, and describes the four system databases (master, model, msdb, tempdb) that SQL Server uses for different purposes like storing configuration and metadata information.

Uploaded by

Saqib Mayar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

1.4 MS SQL Server (Database and Schema) - Section - 2

This document provides an introduction and overview of SQL and database concepts. It discusses what SQL is, why it is used, different SQL data types, how to log into SQL Server Management Studio, create databases, and describes the four system databases (master, model, msdb, tempdb) that SQL Server uses for different purposes like storing configuration and metadata information.

Uploaded by

Saqib Mayar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Rahmatullah Khuram 8/29/2022 1

KATEB University
Computer Science Department
4th Semester-1401

Subject: RDBMS II
Microsoft SQL Server Management
Lecturer: Rahmatullah Khuram

Rahmatullah Khuram 8/29/2022 2


Section -2

Unit -4
Database and SCHEMA

Rahmatullah Khuram 8/29/2022 3


 Introduction
 Introduction to SQL
 SQL Login Page
 SQL SSMS
 Data Types
 SQL Commands

Rahmatullah Khuram 8/29/2022 4


 Introduction
Structured query Language is used to access,
manipulate and retrieve data from relational
database management systems. In this unit we
will discusses the various SQL objects and SQL
commands. This unit describes the various
data types that you can use in SQL and how to
insert data into tables and view of data in
tables. In addition it also describes how to
update data in the tables and perform deletion
operations on tables.

Rahmatullah Khuram 8/29/2022 5


 What is SQL?
SQL is Structured Query Language, which is a computer
language for storing, manipulating and retrieving data
stored in relational database.
SQL is the standard language for Relation Database
System. All relational database management systems
like MySQL, MS Access, Oracle, Sybase, Informix,
postgres and SQL Server use SQL as standard database
language.
Also, they are using different dialects, such as:
o MS SQL Server using T-SQL,
o Oracle using PL/SQL,
o MS Access version of SQL is called JET SQL (native
format) etc.
 Why SQL?
 Allows users to access data in relational database
management systems.
 Allows users to describe the data.
 Allows users to define the data in database and
manipulate that data.
 Allows to embed within other languages using SQL
modules, libraries & pre-compilers.
 Allows users to create and drop databases and tables.
 Allows users to create view, stored procedure,
functions in a database.
 Allows users to set permissions on tables,
procedures, and views.
 Data Types
The data type are the characteristics of data
stored in the tables. Data types allow you to
specify the type of information that can be
stored in columns of a table. For example you
can specify whether columns should consist of
numeric value or alphanumeric string. Defining
a data type in each columns in a table helps to
prevent incorrect data from entering in a
database. The Various data type that a columns
can hold are:-
Data type Description Storage

char(n) Fixed width character string. Maximum 8,000 characters Defined width

varchar(n) Variable width character string. Maximum 8,000 characters 2 bytes + number of chars

varchar(max) Variable width character string. Maximum 1,073,741,824 characters 2 bytes + number of chars

text Variable width character string. Maximum 2GB of text data 4 bytes + number of chars

nchar Fixed width Unicode string. Maximum 4,000 characters Defined width x 2

nvarchar Variable width Unicode string. Maximum 4,000 characters

nvarchar(max) Variable width Unicode string. Maximum 536,870,912 characters

ntext Variable width Unicode string. Maximum 2GB of text data

bit Allows 0, 1, or NULL

binary(n) Fixed width binary string. Maximum 8,000 bytes

varbinary Variable width binary string. Maximum 8,000 bytes

varbinary(max) Variable width binary string. Maximum 2GB

image Variable width binary string. Maximum 2GB

Rahmatullah Khuram 8/29/2022 9


Data type Description Storage

tinyint Allows whole numbers from 0 to 255 1 byte

smallint Allows whole numbers between -32,768 and 32,767 2 bytes

int Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes

bigint Allows whole numbers between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 8 bytes

numeric(p,s) Fixed precision and scale numbers.Allows numbers from -10^38 +1 to 10^38 –1. 5-17 bytes
The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point).
p must be a value from 1 to 38. Default is 18.
The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default
value is 0

smallmoney Monetary data from -214,748.3648 to 214,748.3647 4 bytes

money Monetary data from -922,337,203,685,477.5808 to 922,337,203,685,477.5807 8 bytes

float(n) Floating precision number data from -1.79E + 308 to 1.79E + 308.The n parameter indicates whether the field should hold 4 or 8 bytes. 4 or 8 bytes
float(24) holds a 4-byte field and float(53) holds an 8-byte field. Default value of n is 53.

real Floating precision number data from -3.40E + 38 to 3.40E + 38 4 bytes


Data type Description Storage

datetime From January 1, 1753 to December 31, 9999 with an accuracy of 8 bytes
3.33 milliseconds
datetime2 From January 1, 0001 to December 31, 9999 with an accuracy of 6-8
100 nanoseconds bytes
smalldatetime From January 1, 1900 to June 6, 2079 with an accuracy of 1 4 bytes
minute
date Store a date only. From January 1, 0001 to December 31, 9999 3 bytes

time Store a time only to an accuracy of 100 nanoseconds 3-5


bytes
datetimeoffset The same as datetime2 with the addition of a time zone offset 8-10
bytes
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
Unicode Character Strings Data Types

DATA TYPE Description


Maximum length of 4,000 characters.( Fixed
nchar
length Unicode)
Maximum length of 4,000 characters.(Variable
nvarchar
length Unicode)
Maximum length of 231characters (SQL Server
nvarchar(max)
2005 only).( Variable length Unicode)
Maximum length of 1,073,741,823 characters. (
ntext
Variable length Unicode )
Binary Data Types

Maximum length of 8,000 bytes(Fixed-


binary
length binary data )
Maximum length of 8,000
varbinary
bytes.(Variable length binary data)
Maximum length of 231 bytes (SQL
varbinary(max) Server 2005 only). ( Variable length
Binary data)
Maximum length of 2,147,483,647
image
bytes. ( Variable length Binary Data)
 Login Page
To access and login to MS SQL Server consider
following steps:
1. Complete the installation process
2. Go to start menu and search for SQL Server
Management Studio (SSMS).
3. Click on SSMS
4. The Login page will appear
5. Type the username and password or keep
the windows authentication credentials.
 Create Database
To create your own databases in SQL Server follow
bellow steps:
1. Click on new query button shown in the picture.
2. Write below command
Syntax: Create Database Database_name
Example: Create Database Student
3. Then click on execute button or press F5 to
execute the command shown in the picture.
4. Refresh to see your new created database on
SQL Database lists.
 System Databases
SQL Server mainly contains four System
Databases
1. Master
2. Model
3. Msdb
4. Tempdb
Each of them is used by SQL Server for
Separate purposes. From all the Databases,
Master Database is the most important
Database.
1. Master Database
Master Database contains information about SQL server
configuration. Without Master database, server can’t be
started. This will store the metadata information about
all other objects(Databases,Stored
Procedure,Tables,Views,etc.) which is Created in the
SQL Server. It will also contain login information of
users. If the master database gets corrupted and is not
recoverable from the backup, then a user has to again
rebuild the master database. Therefore, it is always
recommended to maintain a current backup of the
master database. As everything crucial to SQL server is
stored in the master database, it cannot be deleted as
it is the heart of SQL SERVER.
2. Model Database
The model database sets a template for every
database that was newly created . It serves as a
template for the SQL server in order to create a
new database. When we create a new database, the
data present in model database are moved to new
database to create its default objects which include
tables, stored procedures, etc. Primarily, the
requirement of model database is not specific to
creation of new database only. Whenever the SQL
server starts, the Tempdb is created by using
model database in the form of a template. By
default it does not contain any data.
3. MSDB Database
The msdb database is used mainly by the SQL
server Management Studio, SQL Server Agent
to store system activities like sql server jobs,
mail, service broker, maintenance plans, user
and system database backup history,
Replication information, log shipping .We need
to take a backup of this database for the
proper function of SQL Server Agent Service.
4. TempDB Database
From the name of the database itself, we can
identify the purpose of this database. It can be
accessed by all the users in the SQL Server
Instance. The tempdb is a temporary location for
storing temporary tables(Global and Local) and
temporary stored procedure that hold intermediate
results during the sorting or query processing and
cursors. This Database will be created by SQL
Server instance when the SQL Server service starts.
This database is created using model database.We
cannot take a backup of temp Database.
 Schema in SQL Server
A schema is a collection of database objects
including tables, views, triggers, stored
procedures, indexes, etc. A schema is associated
with a username which is known as the schema
owner, who is the owner of the logically related
database objects. A schema always belongs to one
database. On the other hand, a database may have
one or multiple schemas. An object within a
schema is qualified using the
schema_name.object_name format like
sales.orders. Two tables in two schemas can share
the same name so you may have hr.employees and
sales.employees.
 Built-in schemas in SQL Server
SQL Server provides us with some pre-defined
schemas which have the same names as the built-
in database users and roles, for example: dbo,
guest, sys, and INFORMATION_SCHEMA.
The default schema for a newly created database is
dbo, which is owned by the dbo user account. By
default, when you create a new user with the
CREATE USER command, the user will take dbo as
its default schema.

NOTE:SQL Server reserves the sys and


INFORMATION_SCHEMA schemas for system
objects, therefore, you cannot create or drop any
objects in these schemas.
 Creating the SCHEMA
The CREATE SCHEMA statement allows you to
create a new schema in the current database.
The following illustrates the simplified version of
the CREATE SCHEMA statement:
Syntax: CREATE SCHEMA schema_name
[AUTHORIZATION owner_name]
In the Syntax:
 First, specify the name of the schema that you
want to create in the CREATE SCHEMA clause.
 Second, specify the owner of the schema after
the AUTHORIZATION keyword.
Example: CREATE SCHEMA Customer_Service
Once you execute the statement, you can find the newly created
schema under the Security > Schemas of the database name.
If you want to list all schemas in the current database, you can
query schemas from the sys.schemas as shown in the following
query:
SELECT
s.name AS schema_name,
u.name AS schema_owner FROM
sys.schemas s
INNER JOIN sys.sysusers u ON u.uid =
s.principal_id ORDER BY s.name;
After having the customer_services schema,
you can create objects for the schema. For
example, the following statement creates a
new table named jobs in the customer_services
schema:
CREATE TABLE customer_services.jobs(
job_id INT PRIMARY KEY IDENTITY,
customer_id INT NOT NULL,
description VARCHAR(200),
created_at DATETIME2 NOT NULL);
 Altering the SCHEMA
The ALTER SCHEMA statement allows you to
transfer a securable from a schema to another
within the same database. The following shows
the syntax of the ALTER SCHEMA statement:
Syntax: ALTER SCHEMA target_schema_name
TRANSFER [ entity_type :: ] securable_name;

NOTE: a securable is a resource to which the


Database Engine authorization system controls
access. For instance, a table is a securable.
In this syntax:
 target_schema_name is the name of a schema
in the current database, into which you want
to move the object. Note that it cannot be SYS
or INFORMATION_SCHEMA.
 The entity_type can be Object, Type or XML
Schema Collection. It defaults to Object. The
entity_type represents the class of the entity
for which the owner is being changed.
 object_name is the name of the securable
that you want to move into the
target_schema_name.
If you move a stored procedure, function, view,
or trigger, SQL Server will not change the
schema name of these securables. Therefore, it
is recommended that you drop and re-create
these objects in the new schema instead of
using the ALTER SCHEMA statement for
moving. If you move an object e.g., table or
synonym, SQL Server will not update the
references for these objects automatically. You
must manually modify the references to reflect
the new schema name. For example, if you
move a table that is referenced in a stored
procedure, you must modify the stored
procedure to reflect the new schema name.
 SQL Server ALTER SCHEMA example
First, create a new table named offices in the dbo
schema:

CREATE TABLE dbo.offices


(
office_id INT
PRIMARY KEY IDENTITY,
office_name NVARCHAR(40) NOT NULL,
office_address NVARCHAR(255) NOT NULL,
phone VARCHAR(20),
);
Next, insert some rows into the dob.offices
table:

INSERT INTO
dbo.offices(office_name, office_address)
VALUES
('KABUL AFGHANISTAN','400 North 1st
Street, district3, KA 11001'),
('MAZAR AFGHANISTAN','1070 South 2nd
Street, district4, KA 1200');
Then, create a stored procedure that finds office
by office id:
CREATE PROC usp_get_office_by_id(
@id INT
) AS
BEGIN
SELECT
*
FROM
dbo.offices
WHERE
office_id = @id;
END;
After that, transfer this dbo.offices table to the
sales schema:
ALTER SCHEMA sales TRANSFER
OBJECT::dbo.offices;
If you execute the usp_get_office_by_id stored
procedure, SQL Server will issue an error:

Msg 208, Level 16, State 1, Procedure


usp_get_office_by_id, Line 5 [Batch Start Line
30] Invalid object name 'dbo.offices'.
Finally, manually modify the stored procedure to reflect
the new schema:

ALTER PROC usp_get_office_by_id(


@id INT
) AS
BEGIN
SELECT
*
FROM
sales.offices
WHERE
office_id = @id;
END;
 SQL Server DROP SCHEMA
The DROP SCHEMA statement allows you to
delete a schema from a database. The
following shows the syntax of the DROP
SCHEMA statement:
Syntax:
DROP SCHEMA [IF EXISTS] schema_name;
In this syntax:
First, specify the name of the schema that you
want to drop. If the schema contains any
objects, the statement will fail. Therefore, you
must delete all objects in the schema before
removing the schema.
Second, use the IF EXISTS option to
conditionally remove the schema only if the
schema exists. Attempting to drop a
nonexisting schema without the IF EXISTS
option will result in an error.
Example:
 First, create a new schema named logistics:

CREATE SCHEMA logistics;


GO

 Next, create a new table named deliveries


inside the logistics schema:
CREATE TABLE logistics.deliveries
(
order_id INT
PRIMARY KEY,
delivery_date DATE NOT NULL,
delivery_status TINYINT NOT NULL
);

 Then, drop the schema logistics:


DROP SCHEMA logistics;
SQL Server issued the following error because
the schema is not empty.

Msg 3729, Level 16, State 1, Line 1


Cannot drop schema 'logistics' because it is
being referenced by object 'deliveries'.

After that, drop the table logistics.deliveries:


DROP TABLE logistics.deliveries;
Finally, issue the DROP SCHEMA again to drop
the logistics schema:

DROP SCHEMA IF EXISTS logistics;

Now, you will find that the logistics schema has


been deleted from the database.
Rahmatullah KHURAM 8/29/2022 43
Rahmatullah KHURAM 8/29/2022 44

You might also like