0% found this document useful (0 votes)
284 views125 pages

MS SQL Server Is A Relational Database Management System

MS SQL Server is a relational database management system developed by Microsoft that allows for storing and retrieving data to support applications. It can run on a single computer or across a network. SQL Server includes components like the database engine, Analysis Services, Reporting Services, and Integration Services that allow for creating, maintaining, and analyzing databases as well as generating reports and carrying out extract, transform, and load operations.

Uploaded by

Sridhar Rayakam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
284 views125 pages

MS SQL Server Is A Relational Database Management System

MS SQL Server is a relational database management system developed by Microsoft that allows for storing and retrieving data to support applications. It can run on a single computer or across a network. SQL Server includes components like the database engine, Analysis Services, Reporting Services, and Integration Services that allow for creating, maintaining, and analyzing databases as well as generating reports and carrying out extract, transform, and load operations.

Uploaded by

Sridhar Rayakam
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 125

MS SQL Server is a relational database management system (RDBMS) developed by

Microsoft. This product is built for the basic function of storing retrieving data as required by
other applications. It can be run either on the same computer or on another across a
network.

What is SQL Server?


 It is a software, developed by Microsoft, which is implemented from the specification of
RDBMS.
 It is also an ORDBMS.
 It is platform dependent.
 It is both GUI and command based software.
 It supports SQL (SEQUEL) language which is an IBM product, non-procedural, common
database and case insensitive language.

Usage of SQL Server


 To create databases.
 To maintain databases.
 To analyze the data through SQL Server Analysis Services (SSAS).
 To generate reports through SQL Server Reporting Services (SSRS).
 To carry out ETL operations through SQL Server Integration Services (SSIS).

SQL Server Components


SQL Server works in client-server architecture, hence it supports two types of
components − (a) Workstation and (b) Server.
 Workstation components are installed in every device/SQL Server operator’s machine.
These are just interfaces to interact with Server components. Example: SSMS, SSCM,
Profiler, BIDS, SQLEM etc.
 Server components are installed in centralized server. These are services. Example: SQL
Server, SQL Server Agent, SSIS, SSAS, SSRS, SQL browser, SQL Server full text search
etc.
SQL Server is available in various editions. This chapter lists the multiple editions with
its features.
 Enterprise − This is the top-end edition with a full feature set.
 Standard − This has less features than Enterprise, when there is no requirement of
advanced features.
 Workgroup − This is suitable for remote offices of a larger company.
 Web − This is designed for web applications.
 Developer − This is similar to Enterprise, but licensed to only one user for development,
testing and demo. It can be easily upgraded to Enterprise without reinstallation.
 Express − This is free entry level database. It can utilize only 1 CPU and 1 GB memory, the
maximum size of the database is 10 GB.
 Compact − This is free embedded database for mobile application development. The
maximum size of the database is 4 GB.
 Datacenter − The major change in new SQL Server 2008 R2 is Datacenter Edition. The
Datacenter edition has no memory limitation and offers support for more than 25 instances.
 Business Intelligence − Business Intelligence Edition is a new introduction in SQL Server
2012. This edition includes all the features in the Standard edition and support for advanced
BI features such as Power View and PowerPivot, but it lacks support for advanced
availability features like AlwaysOn Availability Groups and other online operations.
 Enterprise Evaluation − The SQL Server Evaluation Edition is a great way to get a fully
functional and free instance of SQL Server for learning and developing solutions. This
edition has a built-in expiry of 6 months from the time that you install it.

2005 2008 2008 R2 2012 2014

Enterpris

Installation Steps
Step 1 − Download the Evaluation Edition
from http://www.microsoft.com/download/en/details.aspx?id=29066
Once the software is downloaded, the following files will be available based on your
download (32 or 64 bit) option.
ENU\x86\SQLFULL_x86_ENU_Core.box
ENU\x86\SQLFULL_x86_ENU_Install.exe
ENU\x86\SQLFULL_x86_ENU_Lang.box
OR
ENU\x86\SQLFULL_x64_ENU_Core.box
ENU\x86\SQLFULL_x64_ENU_Install.exe
ENU\x86\SQLFULL_x64_ENU_Lang.box
Note − X86 (32 bit) and X64 (64 bit)
Step 2 − Double-click the “SQLFULL_x86_ENU_Install.exe” or
“SQLFULL_x64_ENU_Install.exe”, it will extract the required files for installation in
the“SQLFULL_x86_ENU” or “SQLFULL_x86_ENU” folder respectively.
Step 3 − Click the “SQLFULL_x86_ENU” or “SQLFULL_x64_ENU_Install.exe” folder
and double-click “SETUP” application.
For understanding, here we have used SQLFULL_x64_ENU_Install.exe software.
Step 4 − Once we click on 'setup' application, the following screen will open.
Step 5 − Click Installation which is on the left side of the above screen.

Step 6 − Click the first option of the right side seen on the above screen. The following
screen will open.
Step 7 − Click OK and the following screen pops up.
Step 8 − Click Next to get the following screen.

Step 9 − Make sure to check the product key selection and click Next.
Step 10 − Select the checkbox to accept the license option and click Next.

Step 11 − Select SQL Server feature installation option and click Next.
Step 12 − Select Database engine services checkbox and click Next.
Step 13 − Enter the named instance (here I used TestInstance) and click Next.

Step 14 − Click Next on the above screen and the following screen appears.
Step 15 − Select service account names and start-up types for the above listed
services and click Collation.

Step 16 − Make sure the correct collation selection is checked and click Next.
Step 17 − Make sure authentication mode selection and administrators are checked
and click Data Directories.
Step 18 − Make sure to select the above directory locations and click Next. The
following screen appears.

Step 19 − Click Next on the above screen.


Step 20 − Click Next on the above screen to the get the following screen.
Step 21 − Make sure to check the above selection correctly and click Install.

Installation is successful as shown in the above screen. Click Close to finish.

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.
In order to connect to a remote instance of an SQL Server, you will need this or similar
software. It is used by Administrators, Developers, Testers, etc.
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.
SQL Server Management Studio will be open up as shown in the following snapshot in
either of the above method.
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.
SQL Server allows four types of logins −

 A login based on Windows credentials.


 A login specific to SQL Server.
 A login mapped to a certificate.
 A login mapped to asymmetric key.
In this tutorial, we are interested in logins based on Windows Credentials and logins
specific to SQL Server.
Logins based on Windows credentials allow you to log in to SQL Server using a
Windows username and password. If you need to create your own credentials
(username and password,) you can create a login specific to SQL Server.

First Method – Using SQL Server Management Studio


Step 1 − After connecting to SQL Server Instance, expand logins folder as shown in
the following snapshot.

Step 2 − Right-click on Logins, then click Newlogin and the following screen will open.
Step 3 − Fill the Login name, Password and Confirm password columns as shown in
the above screen and then click OK.
Login will be created as shown in the following image.

Second Method – Using T-SQL Script


Create login yourloginname with password='yourpassword'
To create login name with TestLogin and password ‘P@ssword’ run below the
following query.
Create login TestLogin with password='P@ssword'

Database is a collection of objects such as table, view, stored procedure, function,


trigger, etc.
In MS SQL Server, two types of databases are available.

 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
 Resource (Introduced in 2005 version)
 Distribution (It’s for Replication feature only)

User Databases
User databases are created by users (Administrators, developers, and testers who
have access to create databases).
Following methods are used to create user database.

Method 1 – Using T-SQL Script or Restore Database


Following is the basic syntax for creating database in MS SQL Server.
Create database <yourdatabasename>
OR
Restore Database <Your database name> from disk = '<Backup file
location + file name>

Example
To create database called ‘Testdb’, run the following query.
Create database Testdb
OR
Restore database Testdb from disk =
'D:\Backup\Testdb_full_backup.bak'
Note − D:\backup is location of backup file and Testdb_full_backup.bak is the backup file name

Method 2 – Using SQL Server Management Studio


Connect to SQL Server instance and right-click on the databases folder. Click on new database and
the following screen will appear.
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.
Method 1 – Using SQL Server Management Studio

Example
To run a query to select backup history on database called ‘msdb’, select the msdb
database as shown in the following snapshot.
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.
Exec use msdb
The query will open msdb database. You can execute the following query to select
backup history.
Select * from backupset

Databases in SQL Server


 
There are basically the following two types of databases in SQL Server:

1. System Databases.
2. User Databases.

System Databases in SQL Server


 
System databases are databases that are created when SQL Server is installed. These
databases are used for various operational and management activities for SQL Server.

Types of System Databases


 
There are basically four system databases in SQL
Server, master, msdb, tempdb and model that we can see. Apart from that, there is
one more system database resource database that is hidden and read-only. Let's
move ahead with each system database.
 

 
Figure 1: System Database
 
Master Database in SQL Server
 All the system-level information for a SQL Server record by the master database.
 The dbid (database id ) of master is 1.
 The master database has SIMPLE RECOVERY MODEL.
 It is a very important database and we must have the backup.
 Without the master database the server can't be started.

Assume the master database files are missing or


inaccessible, will SQL Server start or up?
Answer: No, SQL Server will not start because the master database is the important database
and all the configuration and information needed to start the SQL Server is stored in the master
database itself hence without the master database SQL server will not start.

 Master database contains information about the server configuration. We can see the
server configuration with the following query:
select * from sys.sysconfigures;
 Master database contains information about all other databases and their location on
SQL Server. We can see the information with executing the following query:
select * from sys.sysdatabases; or sp_helpdb
 Master database contains information about logins in SQL Server. The following is the
query by which we can see it:
select * from sys.syslogins;
 Master database also contains information about users on SQL Server. The following is
the query to see user details:
select * from sys.sysusers;
 Master and mastlog are the logical file names of master database.
master.mdf ( data file ) and mastlog.ldf are the physical files of master database.

Query to see the physical file location of the master database:

1. SELECT name, physical_name FROM sys.database_files;

MSDB Database in SQL Server


 A MSDB database stores information related to backups, SQL Server Agent
information, SQL Server Jobs, alerts and so on.
 The Dbid of the msdb database is 4.
 The recovery model of a msdb database is SIMPLE.
 We can take backup of a msdb database.
 MSDBData and MSDBLog are the logical file names of a msdb database.
 MSDBData.mdf (data file) and MSDBLog.ldf are the physical files of a msdb
database.
 The same query can be used to see the physical file location of a msdb
database:

1. SELECT name, physical_name FROM sys.database_files; 

TempDB in SQL Server


 It stores temporary objects, like temporary tables, temporary Stored Procedures and
temporary tables to store sorting and so on.
 The dbid of a temp database is 2.
 The recovery model of a temp database is SIMPLE.
 We can't take a backup of a tempdb.
 tempdev and templog are the logical file names of tempdb.
 tempdb.mdf (data file) and templog.ldf are the physical files of a tempdb.
 Same query can be use to see the physical file location of tempdb:

1. SELECT name, physical_name FROM sys.database_files;

 
Figure 7: TempDB Table
 

Why we can't take a backup of a temp database?


 
Answer: Temp databases, as the name says, are used to do temporary operations, such as
tables, Stored Procedures and cursors. Once the operation is over it will be cleared and is
minimally logged. A TempDB is recreated everytime SQL is started, so it is always has a clean
copy of the database hence backup and restore operations are not allowed for a TempDB.

SQL Server Authentication Modes


 
What is Authentication
 
Authentication is a process in which we need credentials, in other words username and word, to
access the SQL Server.

.
 
Figure 1: SQL Server Management Studio (SSMS).
When you open SQL Server Management Studio (SSMS) for very first time you will get
the following three things:

1. Server Type
2. Server Name
3. Authentication

1. Server Type
 
There are the following four types of servers:

a. Database Engine: Used for storing, processing and securing data.


b. Analysis Services: Used for Online Analytical Processing and data mining
functionality.
c. Reporting Services: Used for creating interactive, tabular, graphical, or free-form
reports from relational, multidimensional, or XML-based data sources.
d. Integration Services: Used to do a broad range of data migration tasks. It is a
platform for data integration and workflow applications.
e. 2. Server Name
f.  
g. It can be any name of server by which a server can be identified.
h.  
i. 3. Authentication
j.  
k. As we already discussed, it is a process in which we need credentials, in other
words username and word, to access the SQL Server that is clearly visible in
Figure 3.
l.  

m.
Types of Authentication in SQL Server
 
There are basically the following two types of authentication in SQL Server:

a. Windows authentication
b. Mixed mode Authentication/SQL Server Authentication

a. Windows Authentication
 
Requires a valid Windows username and word to access the SQL Server.
 

b. Mixed mode Authentication


 
A user can login either via SQL Server authentication or Windows authentication mode to
connect to SQL Server.
 
Example of Windows Authentication Mode:
 

Remember
 
Remember that when only Windows Authentication is enabled, you can't login with SQL Server
Authentication or Mixed Mode.
 
Let's make it clear with an example.
 
I have created a new login “yashrox” with SQL Authentication.
 
 
Figure 7: Creating a new login from security tab (Step 1)
 

Figure 8: Choosing SQL Server Authentication/Mixed Mode Authentication for new login
“yashrox” (Step 2)
 
 
Figure 9: New login “yashrox” created with Mixed mode authentication (Step 3)
 
Now to check Mixed Mode / SQL Server Authentication we will log into SQL Server with the
login "yashrox" that was created with SQL Server / Mixed Mode Authentication.
 

 
Figure 10: Trying to login with SQL Server Authentication (Mixed Mode)
 
 
Figure 11: Getting error when trying to login with SQL Server Authentication
 
An error occurred when we tried to login with SQL Server Authentication / Mixed Mode
Authentication. Why this happened is because Mixed Mode / SQL Server Authentication is
not enabled by default as we saw in Figure 5 and Figure 6 also.
 
Resolution
 
The resolution for this problem is to enable the Mixed Mode / SQL Server Authentication, so
let's move ahead to enable the Mixed Mode/SQL Server Authentication.
 

Enabling Mixed Mode/SQL Server Authentication


 
There are two ways to enable Mixed Mode/SQL Server Authentication mode.
 

First Method
 
Step 1
 
Log into SQL Server with Windows authentication mode with the login name
“XYZ\yashwant.kumar" (refer to Figure 4).
 
Step 2
 
Right-click on the Server and then click on properties as in the following:
 

 
Figure 12: Configuring SQL Server Properties for Mixed Mode Authentication
 
Step 3
 
Click on security in the left pane and select SQL Server and Windows Authentication Mode and
click OK to save.
 
 
Figure 13: Enabling Mixed Mode Authentication
 
Step 4
 
Restart SQL Server and try to login with SQL Server Authentication.
 

 
Figure 14: Restarting SQL Server after Enabling Mixed Mode Authentication

SQL Server Logins


The Login Properties page is divided into the following five sections:
1. General
2. Server Roles
3. User Mapping
4. Securables
5. Status

1. General

When we open the General tab of the login properties page we can see the following
information:

a. Login Name: Information about the name of the login including the


authentication types information.
b. Password: It is a password for the login name.
c. Specify Old Password: If we want to change the password. The following is the
procedure to change the password:

1. Right-click on login test1 then click on properties.


2. Delete the old password and enter a new password in the password box.
3. Again enter the new password in the confirm password box.
4. Enable the check box to specify the old password and input the old
password.
5. Click OK. It's done now. Login with new password and check that it's
done.

Figure 7: Demonstration of changing password of login

Second Method – Using T-SQL Script


Create login yourloginname with password='yourpassword'
To create login name with TestLogin and password ‘P@ssword’ run below the
following query.
Create login TestLogin with password='P@ssword'
Database is a collection of objects such as table, view, stored procedure, function,
trigger, etc.
In MS SQL Server, two types of databases are available.

 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
 Resource (Introduced in 2005 version)
 Distribution (It’s for Replication feature only)

User Databases
User databases are created by users (Administrators, developers, and testers who
have access to create databases).
Following methods are used to create user database.

Method 1 – Using T-SQL Script or Restore Database


Following is the basic syntax for creating database in MS SQL Server.
Create database <yourdatabasename>
OR
Restore Database <Your database name> from disk = '<Backup file
location + file name>

Example
To create database called ‘Testdb’, run the following query.
Create database Testdb
OR
Restore database Testdb from disk =
'D:\Backup\Testdb_full_backup.bak'
Note − D:\backup is location of backup file and Testdb_full_backup.bak is the backup
file name

Method 2 – Using SQL Server Management Studio


Connect to SQL Server instance and right-click on the databases folder. Click on new
database and the following screen will appear.
T
o remove your database from MS SQL Server, use drop database command.
Following two methods can be used for this purpose.

Method 1 – Using T-SQL Script


Following is the basic syntax for removing database from MS SQL Server.
Drop database <your database name>

Example
To remove database name ‘Testdb’, run the following query.
Drop database Testdb

Method 2 – Using MS SQL Server Management Studio


Connect to SQL Server and right-click the database you want to remove. Click delete
command and the following screen will appear.
Click OK to remove the database (in this example, the name is Testdb as shown in the
above screen) from MS SQL Server.
Backup is a copy of data/database, etc. Backing up MS SQL Server database is
essential for protecting data. MS SQL Server backups are mainly three types − Full or
Database, Differential or Incremental, and Transactional Log or Log.
Backup database can be done using either of the following two methods.

Method 1 – Using T-SQL

Full Type
Backup database <Your database name> to disk = '<Backup file
location + file name>'

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'
Backup database TestDB to disk = 'D:\TestDB_Full.bak'
The following command is used for differential backup database called 'TestDB' to the location
'D:\' with backup file name 'TestDB_diff.bak'
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'
Backup log TestDB to disk = 'D:\TestDB_log.trn'

Method 2 – Using SSMS (SQL SERVER Management Studio)


Step 1 − Connect to database instance named 'TESTINSTANCE' and expand databases folder
as shown in the following snapshot.
Step 2 − Right-click on 'TestDB' database and select tasks. Click Backup and the following
screen will appear.
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.
Step 4 − Click OK to create 'TestDB' database full backup as shown in the following snapshot.
Restoring is the process of copying data from a backup and applying logged
transactions to the data. Restore is what you do with backups. Take the backup file
and turn it back into a database.
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
The following command is used to restore database called 'TestDB' with backup file
name 'TestDB_Full.bak' which is available in 'D:\' location if you are overwriting the
existed database.
Restore database TestDB from disk = ' D:\TestDB_Full.bak' with
replace
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'

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.

Step 3 − Click OK and the following screen pops up.


Step 4 − Select Files option which is on the top left corner as shown in the following
snapshot.
Step 5 − Select Options which is on the top left corner and click OK to restore 'TestDB'
database as shown in the following snapshot.
User refers to an account in MS SQL Server database which is used to access
database.
Users can be created using either of the following two methods.

Method 1 – Using T-SQL

Syntax
Create user <username> for login <loginname>

Example
To create user name 'TestUser' with mapping to Login name 'TestLogin' in TestDB
database, run the following query.
create user TestUser for login TestLogin
Where 'TestLogin' is the login name which was created as part of the Login creation

Method 2 – Using SSMS (SQL Server Management Studio)


Note − First we have to create Login with any name before creating a user account.
Let’s use Login name called 'TestLogin'.
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.

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.
Step 3 − Click OK to display login name. Again click OK to create 'TestUser' user as
shown in the following snapshot.
Permissions refer to the rules governing the levels of access that principals have to
securables. You can grant, revoke and deny permissions in MS SQL Server.
To assign permissions either of the following two methods can be used.

Method 1 – Using T-SQL

Syntax
Use <database name>
Grant <permission name> on <object name> to <username\principle>

Example
To assign select permission to a user called 'TestUser' on object called 'TestTable' in
'TestDB' database, run the following query.
USE TestDB
GO
Grant select on TestTable to TestUser

Method 2 – Using SSMS (SQL Server Management Studio)


Step 1 − Connect to instance and expand folders as shown in the following snapshot.

Step 2 − Right-click on TestUser and click Properties. The following screen appears.
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.
Step 4 Select checkbox for Grant column under Select permission and click OK as
shown in the above snapshot.
Step 5 Select permission on 'TestTable' of TestDB database granted to 'TestUser'.
Click OK.
MS SQL Server provides the following two services which is mandatory for databases
creation and maintenance. Other add-on services available for different purposes are
also listed.

 SQL Server
 SQL Server Agent

Start Services
To start any of the services, either of the following two methods can be used.

Method 1 – Services.msc
Step 1 − Go to Run, type services.msc and click OK. The following screen appears.
Step 2 − To start service, right-click on service, click Start button. Services will start as
shown in the following snapshot.

Method 2 – SQL Server Configuration Manager


Step 1 − Open configuration manager using the following process.
Start → All Programs → MS SQL Server 2012 → Configuration Tools → SQL Server
configuration manager.
Step 2 − Select the service name, right-click and click on start option. Services will
start as shown in the following snapshot.

Stop Services
To stop any of the services, either of the following three methods can be used.

Method 1 - Services.msc
Step 1 − Go to Run, type services.msc and click OK. The following screen appears.

Step 2 − To stop services, right-click on service and click Stop. The selected service
will be stopped as shown in the following snapshot.
Method 2 – SQL Server Configuration Manager
Step 1 − Open configuration manager using the following process.
Start → All Programs → MS SQL Server 2012 → Configuration Tools → SQL Server
configuration manager.

Step 2 − Select the service name, right-click and click Stop option. The selected
service will be stopped as shown in the following snapshot.

Method 3 – SSMS (SQL Server Management Studio)


Step 1 − Connect to the instance as shown in the following snapshot.
Step 2 − Right-click on instance name and click Stop option. The following screen
appears.
Step 3 − Click Yes button and the following screen will open.

Step 4 − Click Yes option on the above screen to stop SQL Server agent service. The
services will be stopped as shown in the following screenshot.
Note
 We cannot use the SQL Server Management Studio method to start the Services as unable
to connect due to services already stopped state.
 We cannot exclude stopping SQL Service agent service while stopping SQL Server service
as SQL Server Agent Service is a dependent service.

SQL Server Create Datatabase


In SQL Server, you have to create a database first before creating a table.

Go to SQL Server Management Studio. You will see a Database.


Right click on the databases and you will see new database. Create a new database.
 
Name your database.

For example:

Create a database "javatpoint".


 
You can see that a database is created as "javatpoint".
MS SQL Server Select Database
SQL Server select database specifies your database in which you want to create your table
and further operations.
SQL Server Create Table
Go to your created database and expand. You will see its "Tables" encircled in red as
following:

Right click on "Tables" and you will see New Table. Click on New Table and you will see the
following page:
You can add Column Name and Datatype as amay may as you want. Every time you fill one
entry, another entry will be automatically created.
How to save the table:

Go to the encircled area and right click there, you will see like following image:
Now click on the "Save Table" and save the table by any name. For example: Let's save the
table by "STUDENT" name.
Now a table "STUDENT" is created.

See the created table:


SQL Server Delete Table
You can delete a table by using SQL Server Managaement studio.

The DELETE statement is used to delete table from the database.


 
Table is deleted now. You can verify it by checking your created database "javatpoint".
There is no table such as "STUDENT"
SQL Server Insert Data
In SQL Server database, INSERT statement is used to insert a single record or multiple
records into a table.

Syntax:

1. INSERT INTO [database_name].[dbo].[table_name]  
2. (column1, column2, ... )  
3. VALUES  
4. (expression1, expression2, ... ),  
5. (expression1, expression2, ... ),  
6. ...;   

Example:

Insert some records in "STUDENT" table:

1. INSERT INTO [javatpoint].[dbo].[STUDENT]  
2.            ([ID]  
3.            ,[NAME]  
4.            ,[AGE]  
5.            ,[SALARY])  
6.      VALUES  
7.            (1,'Ajeet',27,20000),   
8.            (2,'Backon',29,28000),  
9.            (3,'Chris',17,25000);  

You can directly use the above command in a New Query or follow the management studio
screenshots given below:
 
View Inserted Data:
Output:
You can see that all three records are inserted now in the "Student" table.

SQL Server Insert Data


In SQL Server database, INSERT statement is used to insert a single record or multiple
records into a table.

Syntax:

1. INSERT INTO [database_name].[dbo].[table_name]  
2. (column1, column2, ... )  
3. VALUES  
4. (expression1, expression2, ... ),  
5. (expression1, expression2, ... ),  
6. ...;   

Example:
Insert some records in "STUDENT" table:

1. INSERT INTO [javatpoint].[dbo].[STUDENT]  
2.            ([ID]  
3.            ,[NAME]  
4.            ,[AGE]  
5.            ,[SALARY])  
6.      VALUES  
7.            (1,'Ajeet',27,20000),   
8.            (2,'Backon',29,28000),  
9.            (3,'Chris',17,25000);  

You can directly use the above command in a New Query or follow the management studio
screenshots given below:
 
View Inserted Data:
Output:
You can see that all three records are inserted now in the "Student" table.

SQL Server DELETE Data


In SQL Server database, DELETE statement is used to delete records from the table.
Syntax:

1. SELECT TOP 1000 [ID]  
2.       ,[NAME]  
3.       ,[AGE]  
4.       ,[SALARY]  
5.   FROM [javatpoint].[dbo].[STUDENT]  

Use the SQL Server management Studio:

Follow the management studio screenshots given below:


Use the following command:

1. DELETE FROM [javatpoint].[dbo].[STUDENT]  
2.       WHERE ID =3;  
Here one row is deleted where ID=3. You can verify it:

Output:
SQL Server DELETE Top Statement
In SQL Server, DELETE TOP statement is used to delete the records from a table and limit
the number of records deleted regarding a fixed value or percentage.

Syntax:

1. DELETE TOP (top_value) [ PERCENT ]   
2. FROM [database_name].[dbo].[table_name]  
3. [WHERE conditions];   

Parameter explanation
table: It specifies a table that you want to delete records from.

WHERE conditions: It is optional. The conditions that must be met for the records to be
deleted.

TOP (top_value): It is used to delete the top number of rows in the result set based on
top_value. For example, TOP(10) would delete the top 10 rows matching the delete criteria.

PERCENT: It is optional. It is used to delete the percentage of of top rows. For example,
TOP(10) PERCENT would delete the top 10% of the records matching the delete criteria.
DELETE using TOP keyword
TOP keyword is used with DELETE statement to delete the specified top rows of a table.

Example:

We have a table "Employees", having the following data.

Delete top 2 rows from the table "Employees" where salary is greater than or equal to
20000.

Syntax:
1. DELETE TOP(2)  
2. FROM [javatpoint].[dbo].[Employees]  
3. WHERE salary >= 20000;  

You can see that 2 rows are affected. Now see the output:

Output:
DELETE using TOP Percent Keyword
TOP percent keyword is used to delete the rows according to the percentage.

Example:

Delete TOP 25% rows from the table where salary is greater than 20000.

1. DELETE TOP(25) PERCENT  
2. FROM [javatpoint].[dbo].[Employees]  
3. WHERE salary > 20000;   
You can see that 3 rows are affected. 3 is exactly 25% of 12 which is the number of
inserted rows.

Output:
SQL Server DELETE Top Statement
In SQL Server, DELETE TOP statement is used to delete the records from a table and limit
the number of records deleted regarding a fixed value or percentage.

Syntax:

1. DELETE TOP (top_value) [ PERCENT ]   
2. FROM [database_name].[dbo].[table_name]  
3. [WHERE conditions];   

Parameter explanation
table: It specifies a table that you want to delete records from.
WHERE conditions: It is optional. The conditions that must be met for the records to be
deleted.

TOP (top_value): It is used to delete the top number of rows in the result set based on
top_value. For example, TOP(10) would delete the top 10 rows matching the delete criteria.

PERCENT: It is optional. It is used to delete the percentage of of top rows. For example,
TOP(10) PERCENT would delete the top 10% of the records matching the delete criteria.

DELETE using TOP keyword


TOP keyword is used with DELETE statement to delete the specified top rows of a table.

Example:

We have a table "Employees", having the following data.


Delete top 2 rows from the table "Employees" where salary is greater than or equal to
20000.

Syntax:

1. DELETE TOP(2)  
2. FROM [javatpoint].[dbo].[Employees]  
3. WHERE salary >= 20000;  
You can see that 2 rows are affected. Now see the output:

Output:
DELETE using TOP Percent Keyword
TOP percent keyword is used to delete the rows according to the percentage.

Example:

Delete TOP 25% rows from the table where salary is greater than 20000.

1. DELETE TOP(25) PERCENT  
2. FROM [javatpoint].[dbo].[Employees]  
3. WHERE salary > 20000;   
You can see that 3 rows are affected. 3 is exactly 25% of 12 which is the number of
inserted rows.

Output:
SQL Server Update Data
In SQL Server database, UPDATE statement is used to update or modify the already
inserted records into a table.

Syntax:

1. UPDATE [javatpoint].[dbo].[STUDENT]  
2.    SET [ID] = <ID, nchar(10),>  
3.       ,[NAME] = <NAME, nchar(10),>  
4.       ,[AGE] = <AGE, nchar(10),>  
5.       ,[SALARY] = <SALARY, nchar(10),>  
6.  WHERE <Search Conditions,,>  
7. GO  

Follow the management studio screenshots given below:

After clicking on "New Query Editor Window", you will see the following query page.
Use the following command:

1. UPDATE [javatpoint].[dbo].[STUDENT]  
2.    SET [ID] = 4,[NAME] = 'Malvika',[AGE] = 18,[SALARY] = 22000  
3.  WHERE ID =2;  
4. GO  
You can see that 1 row is affected. You can verify it:
Output:
You can see that the above records are now updated.

SQL Server DELETE Data


In SQL Server database, DELETE statement is used to delete records from the table.
Syntax:

1. SELECT TOP 1000 [ID]  
2.       ,[NAME]  
3.       ,[AGE]  
4.       ,[SALARY]  
5.   FROM [javatpoint].[dbo].[STUDENT]  

Use the SQL Server management Studio:

Follow the management studio screenshots given below:


Use the following command:

1. DELETE FROM [javatpoint].[dbo].[STUDENT]  
2.       WHERE ID =3;  
Here one row is deleted where ID=3. You can verify it:

Output:
SQL Server DELETE Top Statement
In SQL Server, DELETE TOP statement is used to delete the records from a table and limit
the number of records deleted regarding a fixed value or percentage.

Syntax:

1. DELETE TOP (top_value) [ PERCENT ]   
2. FROM [database_name].[dbo].[table_name]  
3. [WHERE conditions];   

Parameter explanation
table: It specifies a table that you want to delete records from.

WHERE conditions: It is optional. The conditions that must be met for the records to be
deleted.

TOP (top_value): It is used to delete the top number of rows in the result set based on
top_value. For example, TOP(10) would delete the top 10 rows matching the delete criteria.

PERCENT: It is optional. It is used to delete the percentage of of top rows. For example,
TOP(10) PERCENT would delete the top 10% of the records matching the delete criteria.
DELETE using TOP keyword
TOP keyword is used with DELETE statement to delete the specified top rows of a table.

Example:

We have a table "Employees", having the following data.

Delete top 2 rows from the table "Employees" where salary is greater than or equal to
20000.

Syntax:

1. DELETE TOP(2)  
2. FROM [javatpoint].[dbo].[Employees]  
3. WHERE salary >= 20000;  

You can see that 2 rows are affected. Now see the output:

Output:
DELETE using TOP Percent Keyword
TOP percent keyword is used to delete the rows according to the percentage.

Example:

Delete TOP 25% rows from the table where salary is greater than 20000.

1. DELETE TOP(25) PERCENT  
2. FROM [javatpoint].[dbo].[Employees]  
3. WHERE salary > 20000;   
You can see that 3 rows are affected. 3 is exactly 25% of 12 which is the number of
inserted rows.

Output:
What is a Stored Procedure?
 
A SQL stored procedure (SP) is a collection SQL statements and sql command logic, which is
compiled and stored on the database. Stored procedues in SQL allows us to create SQL
queries to be stored and executed on the server. Stored procedures can also be cached and
reused. The main purpose of stored procedures to hide direct SQL queries from the code and
improve performance of database operations such as select, update, and delete data.
 
You can create and execute stored procedures using the Object Explorer in SQL Server or
using SQL Server Management Studio (SSMS).

So if you have an SQL query that you write over and over again, save it as a
stored procedure, and then just call it to execute it.
You can also pass parameters to a stored procedure, so that the stored
procedure can act based on the parameter value(s) that is passed.

Types of stored procedures


 
There are two types of stored procedures available in SQL Server:

1. User defined stored procedures


2. System stored procedures

User defined stored procedures


 
User defined stored procedures are created by database developers or database
administrators. These SPs contains one more more SQL statements to select, update, or delete
records from database tables. User defined stored procedure can take input parameters and
return output parameters. User defined stored procedure is mixture of DDL (Data Definition
Language) and DML (Data Manipulation Language ) commands.
 
User defined SPs are further classified into two types:
 
T-SQL stored procedures: T-SQL (Transact SQL) SPs receive and returns parameters. These
SPs process the Insert, Update and Delete queries with or without parameters and return data
of rows as output. This is one of the most common ways to write SPs in SQL Server.
 
CLR stored procedures: CLR (Common Language Runtime) SPs are written in a CLR based
programming language such as C# or VB.NET and are executed by the .NET Framework.

System stored procedures


 
System stored procedyres are created and executed by SQL Server for the server
administrative activities. Developers usually don't interfere with system SPs.

Stored Procedure Syntax


Create procedure <procedure_Name>
As
Begin
<SQL Statement>
End
Go
Login to SQL Server database
 
Let's login to our SQL Server database, so we can achieve the folowing:

 How to create a SELECT QUERY based stored procedure which return all
records?
 How to create a PARAMETER based SELECT QUERY stored procedure which
return records based on parameters?
 How to create an INSERT query based stored procedure?
 How to create an UPDATE query based stored procedure?
 How to create a DELETE query based stored procedure?

Login in SQL SERVER with your Server Name, Login and Password.
 

 
 
Switch to your database. My database name is MBKTest.
 
 
Empty stored procedure will be created using the following:
 

he empty template created by SQL Server for a SP looks like the following. The
CREATE PROCEDURE SQL command is used to create a procedure, followed by a SP
name and its parameters. The BEGIN and END area is used to define the query for the
operation. This is where you will write a select, update, insert, or delete queries. 

1. -- ================================================  
2. -- Template generated from Template Explorer using:  
3. -- Create Procedure (New Menu).SQL  
4. --  
5. -- Use the Specify Values for Template Parameters   
6. -- command (Ctrl-Shift-M) to fill in the parameter   
7. -- values below.  
8. --  
9. -- This block of comments will not be included in  
10. -- the definition of the procedure.  
11. -- ================================================  
12. SET ANSI_NULLS ON  
13. GO  
14. SET QUOTED_IDENTIFIER ON  
15. GO  
16. -- =============================================  
17. -- Author:      <Author,,Name>  
18. -- Create date: <Create Date,,>  
19. -- Description: <Description,,>  
20. -- =============================================  
21. CREATE PROCEDURE <Procedure_Name, sysname, ProcedureName>   
22.     -- Add the parameters for the stored procedure here  
23.     <@Param1, sysname, @p1> <Datatype_For_Param1, , int> = <
Default_Value_For_Param1, , 0>,   
24.     <@Param2, sysname, @p2> <Datatype_For_Param2, , int> = <
Default_Value_For_Param2, , 0>  
25. AS  
26. BEGIN  
27.     -- SET NOCOUNT ON added to prevent extra result sets fro
m  
28.     -- interfering with SELECT statements.  
29.     SET NOCOUNT ON;  
30.   
31.     -- Insert statements for procedure here  
32.     SELECT <@Param1, sysname, @p1>, <@Param2, sysname, @p2>  
33. END  
34. GO  

How to write comments in SQL SERVER?


 
You can comment in sql server in the following ways,

1. -- (two hyphens / dash) for a single line of comment.


2. start with /* ……. end with  */    for multiline comments.

How to create a SELECT stored procedure?


1. SET ANSI_NULLS ON  
2. GO  
3. SET QUOTED_IDENTIFIER ON  
4. GO  
5. -- =============================================  
6. -- Author:      Manoj Kalla  
7. -- Create date: 18th Nov 2017  
8. -- Description: Return all members  
9. -- =============================================  
10. --Store procedure name is --> stpGetAllMembers  
11. CREATE PROCEDURE stpGetAllMembers  
12. AS  
13. BEGIN  
14.     -- SET NOCOUNT ON added to prevent extra result sets fro
m  
15.     -- interfering with SELECT statements.  
16.     SET NOCOUNT ON;  
17.   
18.     -- Select statements for procedure here  
19.     Select * from tblMembers  
20. END  
21. GO  

Now, press F5 or click on Execute button to execute the SP.


Now go to Programmability -->Stored Procedures, Right Click and select Refresh.
 
You can see in the following image, the new SP called stpGetAllMembers is created.
 

 
Execute stored procedures in SQL Server
 
In below UI, right click on the SP name and select Execute Stored Procedure... to execute a SP.
From here, you can also modify an exisitng SP.
 
To run stored procedure in SQL Server Management Studio, switch to Query window or
CTRL +N to open an new query window and type the following command. 

 Syntax - EXEC <stored procedure name>


 Example - EXEC stpGetAllMembers

Execute a Stored Procedure


EXEC procedure_name;
CREATE PROCEDURE SelectAllCustomers
AS
SELECT * FROM Customers
GO;
EXEC SelectAllCustomers;
What are parameters in stored procedures?
 
Parameters in SPs are used to pass input values and return output values. There are
two types of parameters:

1. Input parameters - Pass values to a stored procedure.


2. Output parameters - Return values from a stored procedure.

How to create a SELECT query SP with parameters?


1. SET ANSI_NULLS ON  
2. GO  
3. SET QUOTED_IDENTIFIER ON  
4. GO  
5. -- =============================================  
6. -- Author:      Manoj Kalla  
7. -- Create date: 20-Nov-2017  
8. -- Description: Return specifc city records  
9. -- =============================================  
10. CREATE PROCEDURE stpGetMembersByCityName  
11.     -- Add the parameters for the stored procedure here  
12.     @CityName nvarchar(30)  
13.       
14. AS  
15. BEGIN  
16.     -- SET NOCOUNT ON added to prevent extra result sets fro
m  
17.     -- interfering with SELECT statements.  
18.     SET NOCOUNT ON;  
19.   
20.     Select * From tblMembers   
21.     where MemberCity like '%'+@CityName+'%'  
22.           
23. END  
24. GO  
25. To run this SP, type the following command in SQL query tool:
26.  
27. EXEC GetMemberByCityName   @CityName = 'mal'
28.  
29. OR from the UI, run the SP and provide the following input.
30.  
31.

 
32.  
How to create a INSERT query based stored procedure?
 
We can use an INSERT INTO SQL query to insert data into a table. The following SQL
statement creates an INSERT SP with three parameters.

1. SET ANSI_NULLS ON  
2. GO  
3. SET QUOTED_IDENTIFIER ON  
4. GO  
5. -- =============================================  
6. -- Author:      Manoj Kalla  
7. -- Create date: 20-Nov-2047  
8. -- Description: To create a new member  
9. -- =============================================  
10. CREATE PROCEDURE stpInsertMember  
11. @MemberName varchar(50),  
12. @MemberCity varchar(25),  
13. @MemberPhone varchar(15)  
14.   
15. AS  
16. BEGIN  
17.     -- SET NOCOUNT ON added to prevent extra result sets fro
m  
18.     -- interfering with SELECT statements.  
19.     SET NOCOUNT ON;  
20.   
21.     Insert into tblMembers (MemberName,MemberCity,MemberPhon
e)   
22.            Values (@MemberName,@MemberCity, @MemberPhone)  
23.   
24. END  
25. GO  

Right click on stored procedure in Object Explorer and select Refresh.


 

 
 
Pass the value of parameter in Execute dialog box. Something like this:
 
 
 
The following code can be used to execute this SP in SSMS. 

1. USE [MBKTest]  
2. GO  
3.   
4. DECLARE @return_value int  
5.   
6. EXEC    @return_value = [dbo].[stpInsertMember]  
7.         @MemberName = N'Mahesh Chand',  
8.         @MemberCity = N'NewYork',  
9.         @MemberPhone = N'9999945121'  
10. SELECT  'Return Value' = @return_value  
11. GO  
12. You can also run the same SP in code.
13.  
14. EXEC stpInsertMember @MemberName = 'Suhana & Ashish Kalla ',
@MemberCity = 'Mumbai ', @MemberPhone = N'9022592774xxx'
How to create an UPDATE quert based stored procedure?
 
Let's create a new SP that will update a table records based on the Member ID column.
The ID is passed as an input parameter. Here is the new SP that uses an
UPDATE..SET..WHERE command.

1. SET ANSI_NULLS ON  
2. GO  
3. SET QUOTED_IDENTIFIER ON  
4. GO  
5. -- =============================================  
6. -- Author:      Manoj Kalla  
7. -- Create date: 20-Nov-2017  
8. -- Description: Update a member detail by ID  
9. -- =============================================  
10. CREATE PROCEDURE stpUpdateMemberByID  
11. @MemberID int,  
12. @MemberName varchar(50),  
13. @MemberCity varchar(25),  
14. @MemberPhone varchar(15)  
15.   
16. AS  
17. BEGIN  
18.     -- SET NOCOUNT ON added to prevent extra result sets fro
m  
19.     -- interfering with SELECT statements.  
20.     SET NOCOUNT ON;  
21.   
22.     UPDATE tblMembers  
23.     Set MemberName = @MemberName,  
24.         MemberCity = @MemberCity,  
25.         MemberPhone = @MemberPhone  
26.     Where MemberID = @MemberID  
27. END  
28. GO  

Right click on stored procedure in the Object Explorer and select Refresh. You will see
the SP is created.
 
Now, Right click on SP name and select Execute stored procedure…. Provide the input
values and execute.
 
 
 
We can use the following command in SSMS. 

1. USE [MBKTest]  
2. GO  
3.   
4. DECLARE @return_value int  
5.   
6. EXEC    @return_value = [dbo].[stpUpdateMemberByID]  
7.         @MemberID = 20,  
8.         @MemberName = N'Nirupama Kalla',  
9.         @MemberCity = N'Mumbai',  
10.         @MemberPhone = N'904512541xxxx'  
11.   
12. SELECT  'Return Value' = @return_value  
13.   
14. GO  

EXEC stpUpdateMemberByID  17,'Gopal Madhavrai','Bikaner','90454564xxx'


 
The results should show you the updated values.
How to create a DELETE query based stored procedure?
 
Let's create a SP that will delete records. The new SP uses a DELETE command and
delete all records that matches provided Member ID.

1. SET ANSI_NULLS ON  
2. GO  
3. SET QUOTED_IDENTIFIER ON  
4. GO  
5. -- =============================================  
6. -- Author:      Manoj Kalla  
7. -- Create date: 21-Nov-2017  
8. -- Description: Delete a Member by Member ID  
9. -- =============================================  
10. CREATE PROCEDURE stpDeleteMemberByMemberID   
11.     @MemberID int  
12. AS  
13. BEGIN  
14.     -- SET NOCOUNT ON added to prevent extra result sets fro
m  
15.     -- interfering with SELECT statements.  
16.     SET NOCOUNT ON;  
17.   
18.     Delete from tblMembers  
19.     where MemberId = @MemberID  
20.       
21. END  
22. GO  

Execute it.
 
Right click on Stored Procedures in the Object Explorer and select Refresh.
 
RUN stored procedure BY UI
 
Now again right click on stored procedure and select Execute stored procedure…
 
As you can see in the image, I passed @MemberID parameter value = 4.
 
 
 
RUN DELETE stored procedure BY MANUALLY (CODING)
 
EXEC stpDeleteMemberByMemberID  2

You might also like