MS SQL
MS SQL
MS SQL
It is also an ORDBMS.
It is platform dependent.
To maintain databases.
To carry out ETL operations through SQL Server Integration Services (SSIS).
1
Instance of SQL Server
An instance is an installation of SQL Server.
Advantages of Instances
To install different versions in one machine.
To reduce cost.
We have classified the architecture of SQL Server into the following parts for
easy understanding
General architecture
2
Memory architecture
General Architecture
Client Where the request initiated.
3
Execution Plan It is like a roadmap, which contains the order of all the
steps to be performed as part of the query execution.
Query Executor This is where the query will be executed step by step
with the help of execution plan and also the storage engine will be
contacted.
SQL OS This lies between the host machine (Windows OS) and SQL
Server. All the activities performed on database engine are taken care of by
SQL OS. SQL OS provides various operating system services, such as
memory management deals with buffer pool, log buffer and deadlock
detection using the blocking and locking structure.
4
Indirect This is new in SQL Server 2012. This also runs in the background
but to meet a user-specified target recovery time for the specific database
where the option has been configured. Once the Target_Recovery_Time for a
given database has been selected, this will override the Recovery Interval
specified for the server and avoid automatic checkpoint on such DB.
Manual This one runs just like any other T-SQL statement, once you issue
checkpoint command it will run to its completion. Manual checkpoint runs for
your current database only. You can also specify the Checkpoint_Duration which
is optional - this duration specifies the time in which you want your checkpoint
to complete.
o Checkpoint also takes place when the recovery model of the DB is bulk-
logged and a minimally logged operation is performed.
o DB Snapshot creation.
Lazy Writer Process Lazy writer will push dirty pages to disk for an entirely
different reason, because it needs to free up memory in the buffer pool. This
happens when SQL server comes under memory pressure. As far as I am
aware, this is controlled by an internal process and there is no setting for it.
5
SQL server constantly monitors memory usage to assess resource
contention (or availability); its job is to make sure that there is a certain
amount of free space available at all times. As part of this process, when it
notices any such resource contention, it triggers Lazy Writer to free up
some pages in memory by writing out dirty pages to disk. It employs Least
Recently Used (LRU) algorithm to decide which pages are to be flushed to
the disk.
Memory Architecture
Following are some of the salient features of memory architecture.
One of the primary design goals of all database software is to minimize disk I/O
because disk reads and writes are among the most resource-intensive
operations.
Memory in windows can be called with Virtual Address Space, shared by Kernel
mode (OS mode) and User mode (Application like SQL Server).
SQL Server "User address space" is broken into two regions: MemToLeave and
Buffer Pool.
Size of MemToLeave (MTL) and Buffer Pool (BPool) is determined by SQL Server
during startup.
The buffer pool is further divided into multiple sections. The most important
ones being the buffer cache (also referred to as data cache) and procedure
cache. Buffer cache holds the data pages in memory so that frequently
accessed data can be retrieved from cache. The alternative would be reading
data pages from the disk. Reading data pages from cache optimizes
6
performance by minimizing the number of required I/O operations which are
inherently slower than retrieving data from the memory.
Procedure cache keeps the stored procedure and query execution plans to
minimize the number of times that query plans have to be generated. You can
find out information about the size and activity within the procedure cache using
DBCC PROCCACHE statement.
System level data structures Holds SQL Server instance level data about
databases and locks.
Log cache Reserved for reading and writing transaction log pages.
Stack space Windows allocates stack space for each thread started by SQL
Server.
File Groups
Database files can be grouped together in file groups for allocation and
administration purposes. No file can be a member of more than one file
group. Log files are never part of a file group. Log space is managed
separately from data space.
There are two types of file groups in SQL Server, Primary and User-defined.
Primary file group contains the primary data file and any other files not
specifically assigned to another file group. All pages for the system tables
are allocated in the primary file group. User-defined file groups are any file
7
groups specified using the file group keyword in create database or alter
database statement.
One file group in each database operates as the default file group. When
SQL Server allocates a page to a table or index for which no file group was
specified when they were created, the pages are allocated from default file
group. To switch the default file group from one file group to another file
group, it should have db_owner fixed db role.
By default, primary file group is the default file group. User should have
db_owner fixed database role in order to take backup of files and file groups
individually.
Files
Databases have three types of files - Primary data file, Secondary data file,
and Log file. Primary data file is the starting point of the database and
points to the other files in the database.
Every database has one primary data file. We can give any extension for the
primary data file but the recommended extension is .mdf. Secondary data
file is a file other than the primary data file in that database. Some
databases may have multiple secondary data files. Some databases may
not have a single secondary data file. Recommended extension for
secondary data file is .ndf.
Log files hold all of the log information used to recover the database.
Database must have at least one log file. We can have multiple log files for
one database. The recommended extension for log file is .ldf.
The location of all the files in a database are recorded in both master
database and the primary file for the database. Most of the time, the
database engine uses the file location from the master database.
Files have two names Logical and Physical. Logical name is used to refer
to the file in all T-SQL statements. Physical name is the OS_file_name, it
must follow the rules of OS. Data and Log files can be placed on either FAT
8
or NTFS file systems, but cannot be placed on compressed file systems.
There can be up to 32,767 files in one database.
Extents
Extents are basic unit in which space is allocated to tables and indexes. An
extent is 8 contiguous pages or 64KB. SQL Server has two types of extents
- Uniform and Mixed. Uniform extents are made up of only single object.
Mixed extents are shared by up to eight objects.
Pages
It is the fundamental unit of data storage in MS SQL Server. The size of the
page is 8KB. The start of each page is 96 byte header used to store system
information such as type of page, amount of free space on the page and
object id of the object owning the page. There are 9 types of data pages in
SQL Server.
Data Data rows with all data except text, ntext and image data.
Page Free Space (PFS) Information about free space available on pages.
9
Log File Architecture
The SQL Server transaction log operates logically as if the transaction log is
a string of log records. Each log record is identified by Log Sequence
Number (LSN). Each log record contains the ID of the transaction that it
belongs to.
Log records for data modifications record either the logical operation
performed or they record the before and after images of the modified data.
The before image is a copy of the data before the operation is performed;
the after image is a copy of the data after the operation has been
performed.
10
Creating or dropping a table or index.
Rollback operations are also logged. Each transaction reserves space on the
transaction log to make sure that enough log space exists to support a
rollback that is caused by either an explicit rollback statement or if an error
is encountered. This reserved space is freed when the transaction is
completed.
The section of the log file from the first log record that must be present for
a successful database-wide rollback to the last-written log record is called
the active part of the log, or the active log. This is the section of the log
required to a full recovery of the database. No part of the active log can
ever be truncated. LSN of this first log record is known as the minimum
recovery LSN (Min LSN).
The SQL Server Database Engine divides each physical log file internally
into a number of virtual log files. Virtual log files have no fixed size, and
there is no fixed number of virtual log files for a physical log file.
The Database Engine chooses the size of the virtual log files dynamically
while it is creating or extending log files. The Database Engine tries to
maintain a small number of virtual files. The size or number of virtual log
files cannot be configured or set by administrators. The only time virtual log
files affect system performance is if the physical log files are defined by
small size and growth_increment values.
The size value is the initial size for the log file and the growth_increment
value is the amount of space added to the file every time new space is
required. If the log files grow to a large size because of many small
increments, they will have many virtual log files. This can slow down
database startup and also log backup and restore operations.
We recommend that you assign log files a size value close to the final size
required, and also have a relatively large growth_increment value. SQL
Server uses a write-ahead log (WAL), which guarantees that no data
modifications are written to disk before the associated log record is written
to disk. This maintains the ACID properties for a transaction.
11
SQL Server Management Studio is a workstation component\client tool that
will be installed if we select workstation component in installation steps.
This allows you to connect to and manage your SQL Server from a graphical
interface instead of having to use the command line.
The following methods are used to open SQL Server Management Studio.
First Method
Start All Programs MS SQL Server 2012 SQL Server Management
Studio
Second Method
Go to Run and type SQLWB (For 2005 Version) SSMS (For 2008 and Later
Versions). Then click Enter.
A login is a simple credential for accessing SQL Server. For example, you
provide your username and password when logging on to Windows or even
your e-mail account. This username and password builds up the credentials.
Therefore, credentials are simply a username and a password.
12
In this tutorial, we are interested in logins based on Windows Credentials
and logins specific to SQL Server.
To create, alter, or remove a SQL Server login, you can take one of two
approaches
Step 2 Right-click on Logins, then click Newlogin and the following screen
will open.
13
Step 3 Fill the Login name, Password and Confirm password columns as
shown in the above screen and then click OK.
To create login name with TestLogin and password P@ssword run below
the following query.
14
Create login TestLogin with password='P@ssword'
System databases
User Databases
System Databases
System databases are created automatically when we install MS SQL
Server. Following is a list of system databases
Master
Model
MSDB
Tempdb
User Databases
User databases are created by users (Administrators, developers, and
testers who have access to create databases).
15
Create database <yourdatabasename>
OR
Restore Database <Your database name> from disk = '<Backup file location + file name>
Example
OR
16
Enter the database name field with your database name (example: to
create database with the name Testdb) and click OK. Testdb database will
be created as shown in the following snapshot.
17
Select your database based on your action before going ahead with any of
the following methods.
To run a query to select backup history on database called msdb, select the
msdb database as shown in the following snapshot.
18
Method 2 Using T-SQL Script
Use <your database name>
Example
To run your query to select backup history on database called msdb, select
the msdb database by executing the following query.
The query will open msdb database. You can execute the following query to
select backup history.
19
To remove your database from MS SQL Server, use drop database
command. Following two methods can be used for this purpose.
Example
20
Click OK to remove the database (in this example, the name is Testdb as
shown in the above screen) from MS SQL Server.
21
MS SQL Server - Create Users
Example
Where 'TestLogin' is the login name which was created as part of the Login
creation
Step 1 Connect SQL Server and expand databases folder. Then expand
database called 'TestDB' where we are going to create the user account and
expand the security folder. Right-click on users and click on the new user to
see the following screen.
22
Step 2 Enter 'TestUser' in the user name field and click on ellipse to
select the Login name called 'TestLogin' as shown in the following snapshot.
23
Step 3 Click OK to display login name. Again click OK to create 'TestUser'
user as shown in the following snapshot.
24
25
MS SQL Server - Creating Backups
Backup database can be done using either of the following two methods.
Differential Type
Backup database <Your database name> to
disk = '<Backup file location + file name>' with differential
Log Type
Backup log <Your database name> to disk = '<Backup file location + file name>'
Example
The following command is used for full backup database called 'TestDB' to
the location 'D:\' with backup file name 'TestDB_Full.bak'
26
Backup database TestDB to disk = 'D:\TestDB_diff.bak' with differential
The following command is used for Log backup database called 'TestDB' to
the location 'D:\' with backup file name 'TestDB_log.trn'
27
Step 2 Right-click on 'TestDB' database and select tasks. Click Backup
and the following screen will appear.
28
Step 3 Select backup type (Full\diff\log) and make sure to check
destination path which is where the backup file will be created. Select
options at the top left corner to see the following screen.
29
Step 4 Click OK to create 'TestDB' database full backup as shown in the
following snapshot.
30
31
MS SQL Server - Restoring Databases
The Restore database option can be done using either of the following two
methods.
Method 1 T-SQL
Syntax
Restore database <Your database name> from disk = '<Backup file location + file name>'
Example
If you are creating a new database with this restore command and there is
no similar path of data, log files in target server, then use move option like
the following command.
Make sure the D:\Data path exists as used in the following command for
data and log files.
RESTORE DATABASE TestDB FROM DISK = 'D:\ TestDB_Full.bak' WITH MOVE 'TestDB' TO
'D:\Data\TestDB.mdf', MOVE 'TestDB_Log' TO 'D:\Data\TestDB_Log.ldf'
32
Method 2 SSMS (SQL SERVER Management
Studio)
Step 1 Connect to database instance named 'TESTINSTANCE' and right-
click on databases folder. Click Restore database as shown in the following
snapshot.
Step 2 Select device radio button and click on ellipse to select the backup
file as shown in the following snapshot.
33
Step 3 Click OK and the following screen pops up.
34
Step 4 Select Files option which is on the top left corner as shown in the
following snapshot.
35
Step 5 Select Options which is on the top left corner and click OK to
restore 'TestDB' database as shown in the following snapshot.
36
37
MS SQL Server - Assign Permissions
Example
USE TestDB
GO
Grant select on TestTable to TestUser
38
Step 2 Right-click on TestUser and click Properties. The following screen
appears.
39
Step 3 Click Search and select specific options. Click Object types, select
tables and click browse. Select 'TestTable' and click OK. The following screen
appears.
40
Step 4 Select checkbox for Grant column under Select permission and click
OK as shown in the above snapshot.
41
Step 5 Select permission on 'TestTable' of TestDB database granted to
'TestUser'. Click OK.
42
MS SQL Server - Reporting services
Advertisements
Usage
Report is basically used for two purposes - Company Internal Operations
and Company External Operations.
Reporting Services
This is a service which is used to create and publish various kinds of
reports.
Business process
Layout
Query\Procedure\View
The BIDS (Business Intelligence Studio till 2008 R2) and SSDT (SQL Server
Data Tools from 2012) are environment to develop reports.
Step 1 Open either BIDS\SSDT based on the version from the Microsoft
SQL Server programs group. The following screen will appear. In this case,
SSDT has opened.
43
Step 2 Go to file at the top left corner in the above screenshot. Click New
and select project. The following screen will open.
44
Step 3 In the above screen, select reporting services under business
intelligence at the top left corner as shown in the following screenshot.
45
Step 4 In the above screen, select either report server project wizard (it
will guide you step by step through wizards) or report server project (it will
be used to select customized settings) based on your requirement to
develop the report.
46