0% found this document useful (0 votes)
55 views31 pages

Unit 4 - Rdbms Notes

Uploaded by

firdaushjahan17
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
55 views31 pages

Unit 4 - Rdbms Notes

Uploaded by

firdaushjahan17
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 31

UNIT - 4

SQL SERVER BASICS

Microsoft SQL Server 2019


Microsoft SQL Server 2019 is a powerful and versatile database
management system (DBMS) designed to handle a wide range of
data workloads, from small-scale applications to large-scale
enterprise solutions. It offers a robust set of features and tools for
data storage, retrieval, analysis, and reporting.

Key Features and Components:

1. Database Engine:
1. Core component for storing, processing, and securing
data.
2. Supports relational data, XML data, and spatial data.
3. Provides advanced features like full-text search, data
compression, and encryption.
2. Analysis Services:

1. Enables data mining, online analytical processing


(OLAP), and reporting.
2. Helps organizations gain insights from their data
through data cubes, data mining models, and reports.
3. Integration Services (SSIS):

1. Data integration and ETL (Extract, Transform, Load)


tool.
2. Used to extract data from various sources, transform it,
and load it into SQL Server or other destinations.
4. Reporting Services (SSRS):

1. Powerful reporting tool for creating and deploying


interactive reports.
2. Allows users to create a variety of reports, including
tabular, matrix, and chart reports.
5. Machine Learning Services:

1. Enables integration of machine learning models into


SQL Server workflows.
2. Supports popular machine learning frameworks like
Python and R.

Key Benefits of SQL Server 2019:

 High Performance: Optimized for both transactional and


analytical workloads.
 Scalability: Can handle large datasets and complex queries
efficiently.
 Security: Robust security features to protect sensitive data.
 Reliability: Proven reliability and stability in mission-critical
environments.
 Integration: Seamless integration with other Microsoft
products and third-party tools.
 Cloud-Ready: Can be deployed on-premises or in the cloud
(Azure).
 Advanced Analytics: Powerful analytics capabilities for
data-driven insights.

Use Cases:

 Enterprise Applications: Core database for large-scale


enterprise applications.
 Business Intelligence: Data warehousing and business
intelligence solutions.
 Web Applications: Back-end database for web applications.
 Data Science and Machine Learning: Platform for data
science and machine learning projects.
 IoT Applications: Processing and analyzing data from IoT
devices.

A Brief History of SQL Server Versions

Microsoft SQL Server has evolved significantly over the years,


offering new features, improved performance, and enhanced
security with each release. Here's a brief overview of some major
versions and their key features:

Early Versions:

 SQL Server 6.5 and 7.0: These early versions laid the
foundation for SQL Server's capabilities, introducing features
like stored procedures, triggers, and distributed
transactions.

Modern Era:

 SQL Server 2000: This version brought significant


improvements, including enhanced performance, scalability,
and security. It also introduced integration services (SSIS)
and analysis services (SSAS) for data integration and
analysis.
 SQL Server 2005: This version marked a major leap forward
with features like Reporting Services (SSRS) for advanced
reporting, CLR integration for custom .NET code, and
improved performance and scalability.
 SQL Server 2008 and 2008 R2: These versions focused on
high availability, disaster recovery, and performance
optimization. They introduced features like database
mirroring, log shipping, and AlwaysOn Availability Groups.
 SQL Server 2012: This version brought significant
advancements in performance, security, and high availability.
It introduced features like columnstore indexes, AlwaysOn
Availability Groups with automatic failover, and improved
integration with cloud platforms.
 SQL Server 2014: This version focused on Big Data, In-
Memory OLTP, and advanced analytics. It introduced
features like In-Memory OLTP for real-time processing and
PolyBase for querying data from Hadoop clusters.
 SQL Server 2016: This version emphasized security,
performance, and cloud integration. It introduced features
like Always Encrypted for enhanced data protection, Stretch
Database for hybrid cloud scenarios, and improved
integration with Azure.
 SQL Server 2017: This version focused on machine
learning, IoT, and containerization. It introduced features like
machine learning services, Linux support, and containerized
deployment options.
 SQL Server 2019: This version further enhanced machine
learning capabilities, improved performance, and introduced
new security features like Always Encrypted with key
management service. It also offers better integration with
Azure and supports big data analytics.
 SQL Server 2022: This latest version focuses on hybrid
cloud, security, and performance. It introduces features like
Azure Arc-enabled SQL Server, enhanced security features
like confidential computing, and improved performance for
both transactional and analytical workloads.

Installing Microsoft SQL Server 2019


Prerequisites:

 Windows Operating System: Ensure you have a


compatible Windows operating system (Windows Server or
Windows 10/11).
 Administrative Privileges: You'll need administrative rights
to install SQL Server.
 Download SQL Server Installation Media: Download the
appropriate SQL Server 2019 edition from the Microsoft
website.

Installation Steps:-
Run the Setup File:

o Double-click the downloaded setup file (e.g.,


SQLServer2019-SSEI-x64.exe).

Installation Center:

o The SQL Server Installation Center will open.


o Choose New SQL Server stand-alone installation
and click Next.

Product Key and License Terms:


o Enter your product key or choose a trial version.
o Accept the license terms and click Next.

Feature Selection:

o Select the features you want to install:


 Database Engine Services: Core database
engine.
 Management Tools: Tools for managing SQL
Server instances.
 Analysis Services: Data analysis and business
intelligence tools.
 Integration Services: Data integration and ETL
tools.
 Reporting Services: Report generation and
delivery tools.

Instance Configuration:

o Choose the instance type:


 Default: Installs SQL Server with the default
instance name (SQL Server).
 Named Instance: Allows you to specify a custom
instance name.

Server Configuration:

o Configure server settings, such as:


 Server Configuration: Set options like maximum
memory, processor affinity, and recovery model.
 Database Engine Services: Specify the service
account and startup mode.
 SQL Server Agent: Configure the SQL Server
Agent service for scheduled tasks and alerts.

Database Engine Configuration:

o Configure database engine settings, such as:


 Data Directories: Specify the location for data
files and log files.
 Error Logs: Configure error log settings.
 Maximum Server Memory: Set the maximum
amount of memory SQL Server can use.

1. Installation:

 Click Install to start the installation process.

1. Configuration:

 After the installation is complete, configure any additional


settings as needed.

Post-Installation:

 Configure SQL Server Management Studio (SSMS): This


tool is used to manage and administer SQL Server
instances.
 Create Databases: Create databases to store your data.
 Set Up Security: Configure security settings, such as user
accounts and permissions.
 Optimize Performance: Tune database performance by
optimizing queries, indexes, and hardware configurations.

By following these steps and considering your specific needs, you


can successfully install and configure Microsoft SQL Server 2019.

SQL Server Management Studio (SSMS): A


Comprehensive Overview
SQL Server Management Studio (SSMS) is a powerful graphical
tool designed to manage and administer Microsoft SQL Server
databases. It provides a user-friendly interface for various tasks,
including:

 Database Creation and Management:


o Create, modify, and delete databases.
o Manage database properties, such as compatibility
level and recovery model.
o Backup and restore databases.
 Object Management:
o Create, modify, and delete tables, views, stored
procedures, functions, and triggers.
o Manage indexes, constraints, and permissions.
 Query Execution:

o Write and execute SQL queries.


o View query results in various formats (grid, text, XML).
o Analyze query performance and optimize execution
plans.
 Data Import and Export:

o Import data from various sources, such as Excel, CSV,


and other databases.
o Export data to various formats.
 Security Management:

o Create and manage user accounts and roles.


o Assign permissions to users and roles.
 Reporting Services:

o Create and manage reports.


o Deploy reports to a report server.
 Integration Services:

o Design and execute ETL (Extract, Transform, Load)


processes.

Key Features of SSMS:

 Object Explorer: A hierarchical view of database objects,


allowing easy navigation and management.
 Query Editor: A powerful editor for writing and executing
SQL queries.
 SQL Server Agent: A tool for scheduling and automating
tasks, such as backups, data imports, and custom scripts.
 Performance Monitoring: Monitor database performance
metrics, such as CPU usage, memory usage, and disk I/O.
 Security Center: Manage security settings, including user
accounts, roles, and permissions.
 Integration Services Designer: Design and execute ETL
processes visually.
 Reporting Services Designer: Create and deploy reports.

Using SSMS Effectively:

1. Connect to SQL Server: Establish a connection to your


SQL Server instance using the appropriate authentication
method (Windows Authentication or SQL Server
Authentication).
2. Explore the Object Explorer: Navigate through the
database hierarchy to access objects like databases, tables,
and views.
3. Write and Execute Queries: Use the Query Editor to write
and execute SQL queries.
4. Manage Database Objects: Create, modify, and delete
database objects using the Object Explorer or right-click
menus.
5. Monitor Performance: Use the Performance Monitor to
track database performance metrics.
6. Configure Security: Manage user accounts, roles, and
permissions to secure your database.
7. Utilize SSIS and SSRS: Design and deploy ETL processes
and reports.

Azure Data Studio (ADS): A Powerful Tool for


Database Management
Azure Data Studio (ADS) is a modern, cross-platform database
tool designed for managing SQL Server, Azure SQL Database,
and Azure Synapse Analytics. It provides a rich set of features for
database development, administration, and query execution.

Key Features of Azure Data Studio:

Query Editor:

1. Intelligent Code Completion: Autocompletes


keywords, functions, and object names.
2. Syntax Highlighting: Improves code readability.
3. Query Execution Plans: Visualizes query execution
plans to identify performance bottlenecks.
4. Query History: Saves and re-executes frequently
used queries.

Object Explorer:

1. Hierarchical View: Provides a hierarchical view of


databases, schemas, tables, views, stored procedures,
and other objects.
2. Right-Click Actions: Allows you to perform various
actions on database objects, such as editing, deleting,
and executing queries.
3. Drag-and-Drop Functionality: Enables easy object
creation and management.

Data Exploration:

1. Query Results Grid: Displays query results in a clear


and organized manner.
2. Data Export: Exports data to various formats,
including CSV, Excel, and JSON.
3. Data Import: Imports data from various sources, such
as CSV files and Azure Storage.

Database Administration:

1. Database Creation and Management: Create,


modify, and delete databases.
2. Backup and Restore: Backup and restore databases
to ensure data integrity.
3. Security Management: Manage user accounts, roles,
and permissions.
4. Performance Tuning: Monitor and optimize database
performance.

Integration with Azure Services:

1. Azure Integration: Seamless integration with Azure


services, such as Azure SQL Database, Azure
Synapse Analytics, and Azure Data Factory.
2. Azure DevOps Integration: Integrate with Azure
DevOps for CI/CD pipelines and source control.
Extensibility:

1. Extensions: Extend ADS's functionality with custom


extensions.
2. Custom Themes: Customize the appearance of ADS
to suit your preferences.

Benefits of Using Azure Data Studio:

 Cross-Platform Support: Available on Windows, macOS,


and Linux.
 Modern User Interface: Intuitive and user-friendly interface.
 Powerful Query Editor: Enhanced query writing and
execution experience.
 Seamless Azure Integration: Easy access to Azure
services.
 Extensibility: Customize the tool to meet your specific
needs.
 Free and Open-Source: Available at no cost.

SQL Server Express:


SQL Server Express is a free, feature-rich edition of Microsoft's
SQL Server database engine. It's designed for small-scale
applications, learning, and development purposes. While it offers a
subset of features compared to the full-fledged versions of SQL
Server, it's still a powerful tool for many use cases.

Key Features of SQL Server Express:

Relational Database Engine:

1. Stores and manages structured data in tables.


2. Supports standard SQL queries for data retrieval and
manipulation.
3. Provides ACID (Atomicity, Consistency, Isolation,
Durability) transactions for data integrity.

Security:
1. Offers robust security features, including user
authentication, role-based access control, and
encryption.
2. Protects sensitive data with strong security measures.

Integration Services (SSIS):

1. Enables data extraction, transformation, and loading


(ETL) processes.
2. Automate data movement and integration between
different data sources.

Reporting Services (SSRS):

1. Create and deploy interactive reports.


2. Visualize data through various report formats, including
tables, charts, and maps.

Full-Text Search:

1. Efficiently search large volumes of text data.


2. Supports complex search queries, including keyword
searches, phrase searches, and proximity searches.

Replication:

1. Replicate data to other servers for data distribution and


disaster recovery.
2. Supports various replication types, including snapshot
replication and transactional replication.

Integration with .NET Framework:

1. Seamlessly integrates with .NET applications.


2. Provides APIs for data access and manipulation.

LocalDB:

1. A lightweight version of SQL Server Express that runs


in user mode.
2. Ideal for development and testing purposes.
Limitations of SQL Server Express:

 Database Size Limit: The maximum database size is 10GB.


 Hardware and Software Limitations: Certain hardware and
software configurations may be restricted.
 Concurrency Limitations: May not be suitable for high-
concurrency, high-traffic applications.
 Limited Advanced Features: Some advanced features,
such as clustering and partitioning, are not available.

Use Cases for SQL Server Express:

 Small-Scale Applications: Web applications, desktop


applications, and mobile apps.
 Learning and Development: A great tool for learning SQL
and database concepts.
 Proof-of-Concept Development: Quickly prototype and test
database-driven applications.
 Personal Databases: Manage personal data, such as
contacts, finances, and collections.

SQL Server Support Lifecycle


Microsoft provides a structured support lifecycle for its products,
including SQL Server. This lifecycle defines the period during
which Microsoft offers various levels of support and updates.
Understanding this lifecycle is crucial for planning upgrades,
migrations, and security measures.

Key Phases of the SQL Server Support Lifecycle:

Mainstream Support:

1. This phase typically lasts for five years after the initial
product release.
2. During this period, Microsoft provides:
1. Regular security updates and patches.
2. Bug fixes and performance improvements.
3. Technical support through various channels.
4. New features and enhancements.
Extended Support:

1. This phase follows mainstream support and typically


lasts for five years.

1. During this period, Microsoft provides:


1. Critical security updates and patches.
2. Limited technical support.
3. No new features or enhancements.

End of Support:

Once a product reaches the end of its extended support phase,


Microsoft no longer provides any support or updates. It's crucial to
migrate to a supported version before this point to ensure security
and continued functionality.

Factors Affecting the Support Lifecycle:

 Product Version: Different versions of SQL Server may


have varying support lifecycles.
 Product Editions: Different editions of SQL Server may
have different support policies.
 Microsoft's Product Lifecycle Policy: Microsoft may adjust
its overall product lifecycle policy, which can impact the
support lifecycle of SQL Server.

Importance of Staying Updated:

 Security: Regular updates address security vulnerabilities,


protecting your database from attacks.
 Performance: Updates often include performance
improvements and optimizations.
 Feature Enhancements: New features and functionalities
can help you achieve more with your database.
 Technical Support: Active support from Microsoft ensures
timely assistance.
DDL Commands

Data Definition Language(DDL) is a subset of SQL and a part


of DBMS(Database Management System). DDL consist of
Commands to commands like CREATE, ALTER, TRUNCATE and
DROP. These commands are used to create or modify the tables
in SQL.

DDL Commands :
In this section, We will cover the following DDL commands as
follows.
1. Create
2. Alter
3. truncate
4. drop
5. Rename

Command-1 :
CREATE :
This command is used to create a new table in SQL. The user
has to give information like table name, column names, and their
datatypes.

Syntax –
CREATE TABLE table_name
(
column_1 datatype,
column_2 datatype,
column_3 datatype,
....
);

Example –
We need to create a table for storing Student information of a
particular College. Create syntax would be as below.
CREATE TABLE Student_info
(
College_Id number(2),
College_name varchar(30),
Branch varchar(10)
);

Command-2 :
ALTER :
This command is used to add, delete or change columns in the
existing table. The user needs to know the existing table name
and can do add, delete or modify tasks easily.

Syntax –
Syntax to add a column to an existing table.
ALTER TABLE table_name
ADD column_name datatype;

Example –
In our Student_info table, we want to add a new column for CGPA.
The syntax would be as below as follows.
ALTER TABLE Student_info
ADD CGPA number;

Command-3 :
TRUNCATE :
This command is used to remove all rows from the table, but the
structure of the table still exists.

Syntax –
Syntax to remove an existing table.
TRUNCATE TABLE table_name;

Example –
The College Authority wants to remove the details of all students
for new batches but wants to keep the table structure. The
command they can use is as follows.
TRUNCATE TABLE Student_info;

Command-4 :
DROP :
This command is used to remove an existing table along with its
structure from the Database.

Syntax –
Syntax to drop an existing table.
DROP TABLE table_name;

Example –
If the College Authority wants to change their Database by
deleting the Student_info Table.
DROP TABLE Student_info;

Command -5
RENAME:
It is possible to change name of table with or without data in it
using simple RENAME command.
We can rename any table object at any point of time.

Syntax –
RENAME TABLE <Table Name> To <New_Table_Name>;

Example:-
If you want to change the name of the table from Employee to
Emp we can use rename command as
RENAME TABLE Employee To EMP;
DML Commands in SQL
DML is an abbreviation of Data Manipulation Language.

The DML commands in Structured Query Language change the


data present in the SQL database. We can easily access, store,
modify, update and delete the existing records from the database
using DML commands.

DML commands fall into one of four primary categories:

 INSERT
 UPDATE
 DELETE
 SELECT

SELECT Command

This command is used to get data out of the database. It helps


users of the database to access from an operating system, the
significant data they need. It sends a track result set from one
tables or more.
Syntax :
SELECT * FROM <table_name>;
Example:
SELECT * FROM students;

INSERT Command

This command is used to enter the information or values into a


row. We can connect one or more records to a single table within
a repository using this instruction.

Syntax:
INSERT INTO <table_name> ('column_name1' <datatype>,
'column_name2' <datatype>)
VALUES ('value1', 'value2');
Example :
INSERT INTO students ('stu_id' int, 'stu_name' varchar(20), 'city'
varchar(20))
VALUES ('1', 'Nirmit', 'Gorakhpur');

UPDATE Command

This command is used to alter existing table records. Within a


table, it modifies data from one or more records. This command is
used to alter the data which is already present in a table.
Syntax:
UPDATE <table_name>
SET <column_name = value>
WHERE condition;
Example:
UPDATE students
SET due_fees = 20000
WHERE stu_name = 'Mini';

DELETE Command

It deletes all archives from a table. This command is used to


erase some or all of the previous table’s records. If we do not
specify the ‘WHERE’ condition then all the rows would be erased
or deleted.
Syntax:
DELETE FROM <table_name>
WHERE <condition>;
Example:
DELETE FROM students
WHERE stu_id = '001';
DCL Commands
Data control language (DCL) is used to access the stored data. It
is mainly used for revoke and to grant the user the required access
to a database.

DDL Commands

The Data Definition Language (DDL) commands are as follows −

GRANT Command

It is employed to grant a privilege to a user. GRANT


command allows specified users to perform specified tasks

Syntax

GRANT privilege_name on objectname to user;

Here,

 Privilege_name
areSELECT,UPDATE,DELETE,INSERT,ALTER,ALL.
 objectname is table name
 user is the name of the user to whom we grant privileges

Example

GRANT SELECT, UPDATE ON employees TO Bhanu

Explanation − Firstly, to give the permissions to user, we have to


use GRANT command. The privileges are SELECT because to
view the records and UPDATE to modify the records.
The objectname is table name which is Employee. The user name
is "bhanu".

REVOKE Command

It is employed to remove a privilege from a user. REVOKE helps


the owner to cancel previously granted permissions.
Syntax

REVOKE privilege_name on objectname from user;

Here,

 Privilege_name
areSELECT,UPDATE,DELETE,INSERT,ALTER,ALL.
 objectname is table name
 user is the name of the user to whom we grant privileges

Example

REVOKE SELECT, UPDATE ON employees TO Bhanu

Explanation − Firstly, to revoke the permissions to user, we have


to use REVOKE command. The privileges Need to revoke
are SELECT because to view the records and UPDATE to modify
the records. The objectname is table name which is Employee.
The user name is "Bhanu".

TCL COMMANDS IN SQL


Transaction Control Language (TCL) is a critical component
of SQL used to manage transactions and ensure data
integrity in relational databases. By using TCL commands, we
can control how changes to the database are committed or
reverted, maintaining consistency across multiple operations.

 TCL stands for Transaction Control Language.


 It’s a subset of SQL used to manage transactions in
a database.

TCL Commands
TCL includes the following commands:

1. COMMIT

 The COMMIT command is used to save all the


transactions to the database that have been performed
during the current transaction.
 Once a transaction is committed, it becomes permanent and
cannot be undone.
 This command is typically used at the end of a series of
SQL statements to ensure that all changes made during the
transaction are saved.

Syntax:
COMMIT;

2. ROLLBACK

 The ROLLBACK command is used to undo all the


transactions that have been performed during the
current transaction but have not yet been committed.
 This command is useful for reverting the database to its
previous state in case an error occurs or if the changes
made are not desired.

Syntax:
ROLLBACK;

3. SAVEPOINT

 The SAVEPOINT command is used to set a point within a


transaction to which we can later roll back.
 This command allows for partial rollbacks within a
transaction, providing more control over which parts of a
transaction to undo.

Syntax:
SAVEPOINT savepoint_name;

Data Constraints
Constraints in SQL

Constraints in SQL means we are applying certain conditions or


restrictions on the database. This further means that before
inserting data into the database, we are checking for some
conditions. If the condition we have applied to the database holds
true for the data which is to be inserted, then only the data will be
inserted into the database tables.

Constraints available in SQL are:

1. NOT NULL
2. UNIQUE
3. PRIMARY KEY
4. FOREIGN KEY
5. CHECK
6. DEFAULT

1. NOT NULL –
If we specify a field in a table to be NOT NULL. Then the field will
never accept null value. That is, you will be not allowed to insert a
new row in the table without specifying any value to this field.
For example, the below query creates a table Student with the
fields ID and NAME as NOT NULL. That is, we are bound to
specify values for these two fields every time we wish to insert a
new row.

CREATE TABLE Student


(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
ADDRESS varchar(20)
);

2. UNIQUE –
This constraint helps to uniquely identify each row in the table. i.e.
for a particular column, all the rows should have unique values.
We can have more than one UNIQUE columns in a table.
For example, the below query creates a table Student where the
field ID is specified as UNIQUE. i.e, no two students can have the
same ID.

CREATE TABLE Student


(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20)
);

3. PRIMARY KEY –
Primary Key is a field which uniquely identifies each row in the
table. If a field in a table as primary key, then the field will not be
able to contain NULL values as well as all the rows should have
unique values for this field. So, in other words we can say that
this is combination of NOT NULL and UNIQUE constraints.
A table can have only one field as primary key. Below query will
create a table named Student and specifies the field ID as
primary key.

CREATE TABLE Student


(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20),
PRIMARY KEY(ID)
);

4. FOREIGN KEY –
Foreign Key is a field in a table which uniquely identifies each row
of a another table. That is, this field points to primary key of
another table. This usually creates a kind of link between the
tables.
Consider the two tables as shown below:

Orders
O_ID ORDER_NO C_ID
1 2253 3
2 3325 3
3 4521 2
4 8532 1

Customers
C_ID NAME ADDRESS
1 RAMESH DELHI
2 SURESH NOIDA
3 DHARMESH GURGAON

As we can see clearly that the field C_ID in Orders table is the
primary key in Customers table, i.e. it uniquely identifies each row
in the Customers table. Therefore, it is a Foreign Key in Orders
table.
Syntax:

CREATE TABLE Orders


(
O_ID int NOT NULL,
ORDER_NO int NOT NULL,
C_ID int,
PRIMARY KEY (O_ID),
FOREIGN KEY (C_ID) REFERENCES Customers(C_ID)
)

5. CHECK –
Using the CHECK constraint we can specify a condition for a field,
which should be satisfied at the time of entering values for this
field.
For example, the below query creates a table Student and
specifies the condition for the field AGE as (AGE >= 18 ). That is,
the user will not be allowed to enter any record in the table with
AGE < 18.

CREATE TABLE Student


(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
AGE int NOT NULL CHECK (AGE >= 18)
);

6. DEFAULT –
This constraint is used to provide a default value for the fields.
That is, if at the time of entering new records in the table if the
user does not specify any value for these fields then the default
value will be assigned to them.
For example, the below query will create a table named Student
and specify the default value for the field AGE as 18.

CREATE TABLE Student


(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
AGE int DEFAULT 18
);

Stored Procedures in SQL Server


A stored procedure in SQL is a group of SQL queries that can be
saved and reused multiple times. It is very useful as it reduces the
need for rewriting SQL queries. It enhances efficiency, reusability,
and security in database management.
Users can also pass parameters to stored procedures so that the
stored procedure can act on the passed parameter values.
Stored Procedures are created to perform one or more DML
operations on the Database. It is nothing but a group of SQL
statements that accepts some input in the form of parameters,
performs some task, and may or may not return a value.

Benefits of Stored Procedures:

Improved Performance:
o Precompilation: SQL Server compiles the stored
procedure once, and the compiled code is stored in the
database. This eliminates the need for repeated
parsing and compilation, leading to faster execution.
o Reduced Network Traffic: By executing complex logic
on the server side, you can reduce the amount of data
transferred between the client and the server.

Enhanced Security:

o Centralized Security: You can grant permissions to


execute stored procedures, limiting access to specific
users or roles.
o Data Hiding: You can encapsulate complex SQL logic
within the stored procedure, hiding the underlying
implementation details.

Reusability:

o Reusable Code: Stored procedures can be called from


multiple applications and scripts, promoting code reuse
and reducing development effort.

Modularity:

o Modular Design: Breaking down complex database


operations into smaller, reusable stored procedures
improves code organization and maintainability.

Syntax
Two important syntaxes for using stored procedures in SQL are:

Syntax to Create a Stored Procedure

CREATE PROCEDURE procedure_name


(parameter1 data_type, parameter2 data_type, …)
AS
BEGIN
— SQL statements to be executed
END
Syntax to Execute the Stored Procedure

EXEC procedure_name parameter1_value,


parameter2_value, ..

Parameter

The most important part is the parameters. Parameters are used to


pass values to the Procedure. There are different types of
parameters, which are as follows:
1. BEGIN: This is what directly executes or we can say that it is
an executable part.
2. END: Up to this, the code will get executed.

Creating a Stored Procedure:

Here's a basic example of creating a stored procedure to retrieve


customer information:

SQL
CREATE PROCEDURE GetCustomersASBEGIN
SELECT CustomerID, CustomerName, City
FROM Customers;END;

Executing a Stored Procedure:

To execute a stored procedure, you can use the EXEC or


EXECUTE statement:

SQL
EXEC GetCustomers;

Parameters in Stored Procedures:


Stored procedures can accept input parameters and return output
parameters. This allows you to create flexible and dynamic
procedures.

SQL
CREATE PROCEDURE GetCustomersByCity
@City NVARCHAR(50)ASBEGIN
SELECT CustomerID, CustomerName
FROM Customers
WHERE City = @City;END;

To execute this procedure with a specific city:

SQL
EXEC GetCustomersByCity @City = 'New York';

Functions
A Function is similar to a stored procedure, but it returns a specific
value. Functions can be scalar-valued or table-valued.

Types of Functions:

Scalar-Valued Functions:

1. Returns a single value.


2. Used for calculations, data manipulation, and
formatting.

Table-Valued Functions:

1. Returns a table of data.


2. Useful for complex calculations and data
transformations.

Benefits of Functions:

 Reusability: Can be used in various SQL statements and


expressions.
 Modularity: Encapsulate complex calculations and data
retrieval logic.
 Performance: Can improve performance by pre-computing
results.

Syntax:

Scalar-Valued Function:

SQL
CREATE FUNCTION FunctionName
(
@Parameter1 DataType,
@Parameter2 DataType,
...
)RETURNS DataTypeASBEGIN
-- SQL statements to calculate the return value
RETURN ValueEND

Table-Valued Function:

SQL
CREATE FUNCTION FunctionName
(
@Parameter1 DataType,
@Parameter2 DataType,
...
)RETURNS TABLEASRETURN
(
SELECT Column1, Column2, ...
FROM TableName
WHERE ...
)

Example (Scalar-Valued Function):

SQL
CREATE FUNCTION CalculateDiscount
(@Price DECIMAL(10,2), @DiscountPercentage
INT)RETURNS DECIMAL(10,2)ASBEGIN
DECLARE @DiscountedPrice DECIMAL(10,2)
SET @DiscountedPrice = @Price - (@Price *
@DiscountPercentage / 100)
RETURN @DiscountedPriceEND

Example (Table-Valued Function):

SQL
CREATE FUNCTION GetTopCustomers
(@TopN INT)RETURNS TABLEASRETURN
(
SELECT TOP(@TopN) CustomerID, CustomerName,
TotalPurchases
FROM Customers
ORDER BY TotalPurchases DESC
)

Difference between Stored procedure and


Function

Below we have listed down some of the differences between


stored procedure and function in PL/SQL:

Stored Procedure Function

May or may not returns a value to the Returns a value to the calling part of the
calling part of program. program.

Uses IN, OUT, IN OUT parameter. Uses only IN parameter.

Returns a value using “ OUT” Returns a value using “RETURN”.


parameter.

Does not specify the datatype of the Necessarily specifies the datatype of the
value if it is going to return after a value which it is going to return after a
calling made to it. calling made to it.

Cannot be called from the function Can be called from the procedure block
block of code. of code.

You might also like