0% found this document useful (0 votes)
54 views130 pages

SQL Server

This document provides an overview of Microsoft SQL Server, including definitions of key concepts like data, databases, database management systems (DBMS), and the evolution of DBMS from flat file databases to relational and NoSQL databases. It describes SQL commands like DDL, DML, DCL, and TCL. It also covers SQL Server concepts like creating databases and tables, altering tables, inserting data, temporary tables, variables, aliases, and data types.

Uploaded by

kumarmadhavan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
54 views130 pages

SQL Server

This document provides an overview of Microsoft SQL Server, including definitions of key concepts like data, databases, database management systems (DBMS), and the evolution of DBMS from flat file databases to relational and NoSQL databases. It describes SQL commands like DDL, DML, DCL, and TCL. It also covers SQL Server concepts like creating databases and tables, altering tables, inserting data, temporary tables, variables, aliases, and data types.

Uploaded by

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

Microsoft SQL Server

Data Is...more than just data!


Data is a collection of facts, such as numbers, words, measurements, observations
or even just descriptions of things.

Data is defined as reinterpretable representation of information in a formalized


manner suitable for communication, interpretation, or processing

Ex – your name and DOB .


Database :
Systematically organized or structured repository of indexed information (usually as a group of linked
data files) that allows easy retrieval, updating, analysis, and output of data.

Database Management System :


A database management system (DBMS) is a collection of programs that enables you to store
modify, and extract information from a database.

Types of DBMS:
- Flat File Database.
- Relational Database Management system(RDBMS).
- NoSQL
Evolution of Database Management System:
Flat File Database :
• This is probably the easiest to understand but at present rarely used. You can think of this as a
single huge table. Such type of datasets were used long back in 1990s, when data was only used
to retrieve information in case of concerns. Very primitive analytics were possible on these
database.

Relational Database : * Normalization

• A relational database is a collection of data items organized as a set of formally-


described tables from which data can be accessed or reassembled in many different ways
without having to reorganize the database tables.
• Every table shares at least one field with another table in 'one to one,' 'one to many,' or 'many
to many' relationships.
• Examples :
- Oracle - SQL
- DB 2 - Informix
- MySQL - mSQL
- Teradata - PostgreSQL
NoSQL
• When people realized that unstructured text carry tons of information which they are unable to mine using
RDBMS, they started exploring ways to store such datasets. Anything which is not RDBMS today is loosely
known as NoSQL. After social networks gained importance in the market, such database became common
in the industry.
• Examples :
- MongoDB - CoughDB
- RedisDB - Hbase
- Cassandra
Query
• Set of commands used in retrieving data from (or modifying or
updating) a database.
• Types of Querying language:
• - TSQL
• - PL/SQL
• - JetSQL
Microsoft SQL Server :
• Microsoft SQL Server is a Relational Database Management System (RDBMS) developed by Microsoft. It is
a highly scalable product that can be run on anything from a single laptop, to a network of high-powered
cloud servers, and anything in between.
History of MS-SQL Server:
Version Year
SQL Server 1.0 (16bit) 1989
SQL Server 1.1 1991
SQL Server 4.2 (32 bit Edition) 1993
SQL Server 6.5 1996
SQL Server 7.0 1998
SQL Server 2000 2000
SQL Server 2005 2005
SQL Server 2008 2008
SQL Server 2008 R2 2010
SQL Server 2012 2012
SQL Server 2014 2014
SQL Server 2016 2016
SQL Commands :
Types of commands in MS-SQL :
1) DDL
• Data Definition Language (DDL) statements are used to define the database
structure or schema. Some examples:
- Create
- Alter
- Truncate.
- Drop
- Rename

2) DML

• Data Manipulation Language (DML) statements are used for managing data
within schema objects. Some examples:
- Select
- Insert
- Update
- Delete
- Merge
--cont--
3) DCL :
• Data Control Language (DCL) statements. Some examples:
- GRANT
- REVOKE
4) TCL
• Transaction Control (TCL) statements are used to manage the
changes made by DML statements. It allows statements to be
grouped together into logical transactions.
- COMMIT
- SAVEPOINT
- ROLLBACK
- SET TRANSACTION
Create Statement :
Create Database :
• Syntax :
CREATE DATABASE <db_Name>

(or)

CREATE DATABASE <db_Name>


ON
(NAME = <mdf_logical_name>,
FILENAME = <mdf_file_full_path>,
SIZE = <initial_size_mb>,
MAXSIZE = <max_size_mb>,
FILEGROWTH = <growth_size_mb>
)
LOG ON
(
NAME = <ldf_logical_name>,
FILENAME = ‘<log_file_full_path>’,
SIZE = <initial_size_mb>,
MAXSIZE = <max_size_mb>,
FILEGROWTH = <max_size_mb>
• Create table : **using spaces in column name

Syntax
CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
)

• Create Table With Identity Column : * Demo Without using seed

Syntax
CREATE TABLE table_name
(
column_name1 INT IDENTITY(<seed>,<increment>),
column_name2 data_type(size),
column_name3 data_type(size),
....
)

Points to Remember :
 The column data type should be “Integer” , when using identity.
 Defining the Seed and Increment is not mandatory by default it will assign (1,1).
Select Statement :
Syntax :
Select * From <table_name>
Select <column_name_1>, <column_name_2>, <column_name_3> From <table_name>
Select <column_name_1>,* From <table_name>

Alter Statement:
Syntax :

ALTER TABLE <table_name>


ADD <column_name> <data_type>(<length>)

ALTER TABLE <table_name>


ALTER COLUMN <column_name> <data_type>(<length>)

Points to Remember :
 While changing the existing table column data type , you can not do conversion explicitly (Ex : varchar to Int)
Insert Statement:

Syntax :
INSERT INTO table_name
VALUES (value1,value2,value3,...)

INSERT INTO table_name (column1,column2,column3,...)


VALUES (value1,value2,value3,...)

INSERT INTO <table_name>


SELECT * FROM <table_name>

INSERT INTO <table_name_1> (column_name_1,Column_name_2)


SELECT <column_name_1>,<column_name_2> From <table_name_2>

SELECT * INTO <table_name_2> FROM <table_name_1>

Points to Remember :
 You can not insert values for Identity column.
Temporary Tables :
Local Temporary Table:
• LOCAL TEMPORARY TABLES are distinct within modules and embedded SQL programs within SQL Server sessions.
• LOCAL TEMPORARY TABLES are stored in tempdb and SQL Server automatically deletes these tables when they are
no longer used.

Syntax :
CREATE TABLE #table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
)
-- cont --

Global Temporary Table:


• Global TEMPORARY TABLES are distinct within modules and embedded SQL programs within particular connection.

Syntax :
CREATE TABLE ##table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
)

Points to remember :
 You need to manually drop those temporary tables within the session (or) connection.
 While using within the stored procedures it will automatically get dropped , end of the execution .
 What will happen when gives more than hashes(#) for the table name ?
SQL Variables:
Local Variables :
• Must be declared.
• It should start with @
Syntax :
Declare @<variable_name> <data_type><(length)>
Global Variables :
• Global variable names begin with a @@ prefix
• You do not need to declare them, since the server constantly maintains them.
Ex :
- @@ERROR - @@IDENTITY
- @@LANGUAGE - @@ROWCOUNT
- @@SERVERNAME - @@SPID
- @@VERSION

Points to Remember :
 You can assign global variables results to your local variable.
Aliases:
• COLUMN ALIASES are used to make column headings in your result set easier to read.
• TABLE ALIASES are used to shorten your SQL to make it easier to read or when you are performing a joins.

Syntax :
Select <column_name_1> AS <alias_name_a1>,<column_name_1> AS <alias_name_a2>
From <table_name>

Select * From <table_name_1> AS <alias_name_1> JOIN <table_name_2> <alias_name_2>


ON A.<column_name_1> = B.<column_name_2>

Concatenation:
• The plus sign (+) is the string concatenation operator that enables string concatenation.

Syntax :
Select <column_name_1> + <column_name_2> AS <column_name>
From <table_name>

Points to Remember :

 Concatenation is the string function , you can not use this against any other data types . If you really want to perfor concatenation against
any other data types then you need convert those column explicitly to string.
Categories of Data Types in SQL:
and scale - Exact numeric - Approximate numeric Data Types: ** Precision
- Character strings - Unicode character strings
- Date and time - Other Data Types

Exact Numeric :

Data Type Range Storage


bigint -2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807 8 bytes
int -2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647) 4 Bytes
smallint -2^15 (-32,768) to 2^15-1 (32,767) 2 Bytes
tinyint 0 to 255 1 Byte
decimal
numeric
Bit
-- cont –

Approximate Numeric :
- Float
- Real
Date And Time:
- Date Time
- Small Date Time
- Date Time 2
- Time
- Date
Non Unicode Char Strings: ** Concatenation Difference

- Char  Length between 1 to 8000 - Fixed Length Data type - Takes 1 byte for each char
- Varchar  Length between 1 to 8000 - Variable Length Data type - Takes 1 byte for each char
- Text  Unlimited Length - Variable Length - Takes 1 byte for each char
Points to Remember :
 During concatenation of CHAR data type variables, it includes space in-place of unused space in the result of
concatenation.
 ntext, text, and image data types will be removed in a future version of SQL Server. Avoid using these data types in new
development work.
-- cont –

Unicode String Data types :


- Nchar  Length between 1 to 4000 - Fixed Length Data type - Takes 2 Byes for Each Char
- Nvarchar  Length between 1 to 4000 - Variable Length Data type - Takes 2 Bytes for Each Char
- Ntext  Unlimited Length - Variable Length - Takes 2 Bytes for Each Char
Other Data Types :
- Table
- XML

Truncate & Drop & Delete ** Drop not only for Tab & DB

Syntax :
- Truncate Table <table_name>
- Drop Table <Table_name>
- Drop Database <db_Name>
- Delete From Table Where <column_name>= <column_value>
Points to remember :
 TRUNCATE TABLE is similar to the DELETE statement with no WHERE clause; however, TRUNCATE TABLE is faster and
uses fewer system and transaction log resource.
Rename Statement ** Rename not only for tab,column,database

Table Rename :
Syntax :
EXCE SP_RENAME ‘<old_table_name>’ , ‘<new_table_name>’

Column Rename :
Syntax :
EXCE SP_RENAME ‘<table_name>.<old_column_name>’ , ‘<new_column_name>’,’<object_type>’

Database Rename :
Syntax:
EXEC SP_RENAME ‘<old_db_name>’,’<new_db_name>’,’<object_type>’

Points To Remember :
 You need to use Appropriate database while renaming the column (or) table.
 Object type is must while renaming the Database and Columns
SQL Server Functions
Aggregate Functions :
- AVG
- MIN
- MAX
- COUNT
- COUNT_BIG
- SUM

Points To Remember :
 COUNT_BIG works like the COUNT function. The only difference between the two functions is their return values. COUNT_BIG
always returns a bigint data type value. COUNT always returns an int data type value.

Conversion Functions:
- CAST
- CONVERT

Cast :
SYNTAX :
CAST ([Expression] AS DataType)

Conversion :
SYNTAX :
CONVERT(data_type(length), expression, style)
Data Type Function :
- DATALENGTH -> DATALENGTH(<expression>)
- IDENT_CURRENT -> IDENT_CURRENT(‘<table_name>’)
- IDENT_INCR -> IDENT_INCR (‘<table_name>’)
- IDENT_SEED -> IDENT_SEED(‘<table_name>’)

Date Time Functions :


- CURRENT_TIMESTAMP
- DATEADD -- > DATEADD (datepart,number,date)
- DATEDIFF -- > DATEDIFF(datepart,startdate,enddate)
- DATENAME -- > Select (datepart,date)
- DAY -- > Select DAY (date)
- DATEPART -- > Select DATEPART (datepart,date)
- ISDATE --> SELECT ISDATE (expression)
- Month -- > Select MONTH (date)
- Year -- > Select YEAR ( date )
Date Parts in SQL
datepart Abbreviations
year yy, yyyy
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw
hour hh
minute mi, n
second ss, s
millisecond ms
microsecond mcs
nanosecond ns
Mathematical Functions:
- CEILING -> CEILING (<expression>)
- FLOOR -> FLOOR (< expression >)
- ROUND -> ROUND (<expression>)
- ABS -> ABS(<expression>)

Ranking Functions :
- DENSE_RANK()
- RANK ()
- ROW_NUMBER()

ISNULL :
Replaces NULL with the specified replacement value.
ISNULL ( check_expression,replacement_value )
NULLIF:
Returns a null value if the two specified expressions are equal. It returns the first
expression if the two expressions are not equal. NULLIF is equivalent to a searched CASE
function in which the two expressions are equal and the resulting expression is NULL.
Syntax
NULLIF ( expression1 , expression2 )
Points To Remember :
 We recommend that you not use time-dependent functions. This could cause the function to be
evaluated twice and to return different results from the two invocations.
String Functions:
- UPPER
- LOWER
- LEN
- RTRIM
- LTRIM
- LEFT
- RIGHT
- REPLACE
- REVERSE
- SUBSTRING
- CHARINDEX
- STUFF
String Functions:

UNIOIN AND UNION ALL


Union :
Combine 2 or more result sets (removes duplicates).
UNION ALL
Combine 2 or more result sets (includes duplicates).
Points To Remember :
 While using UNION (or) UNION ALL , selected no, of columns should be same for all the datasets
INTERSECT :
Intersection of 2 result sets
EXCEPT
Result set of one minus the result set of another
DISTINCT
Distinct is used to retrieve unique records
WHERE CLAUSE ** Give more examples based on all the things so far seen

Where clause is used to filter the result sets.

ORDER BY Clause
Order by is used to Sorting the query results
TOP Clause
Retrieve records from a table and limit results.
Operators in SQL ** use convert & ISNULL * Exits When subqueries

Comparison Operators Logical Operators


= (Equals) AND
> (Greater Than) OR
< (Less Than) BETWEEN
>= (Greater Than or equal to) IN
<= (Less Than or equal to) LIKE
<> Or != Not Equal To EXITS
!< Not Less Than NOT EXISTS
!> Not Greater Than NOT IN
IS NULL
IS NOT NULL
Wild Cards in SQL % , _
GROUP BY :
The SQL Server (Transact-SQL) GROUP BY clause is used in a SELECT statement to collect data across multiple records and
group the results by one or more columns.
Syntax :
SELECT <COLUMN_NAME>,<AGGREGATE_FUNCTION>(<COLUMN_NAME>) FROM <TABLE_NAME>
GROUP BY <COLUMN_NAME>

HAVING : ** Don’t use any function name as tbl name,column name and all
The SQL Server (Transact-SQL) HAVING clause is used in combination with the GROUP BY clause to restrict the groups of
returned rows to only those whose the condition is TRUE.
Syntax :
SELECT <COLUMN_NAME>,<AGGREGATE_FUNCTION>(<COLUMN_NAME>) FROM <TABLE_NAME>
GROUP BY <COLUMN_NAME>
HAVING <aggregate_function>(column_name) <operator> <Value>

UPDATE STATEMENT :
Update records in a table .
Syntax :
Update <table_name> SET <column_name> = <Value> WHERE <column_name> = <value>
Constraints in SQL:
1) Primary key constraints : ** naming con

In SQL Server (Transact-SQL), a primary key is a single field or combination of fields that uniquely defines a
record. None of the fields that are part of the primary key can contain a null value. A table can have only one
primary key.
A primary key can be defined in either a CREATE TABLE statement or an ALTER TABLE statement.
Syntax :
Create Table <table_name> (<column_name><data_type>,
<column_name><data_type>,
<column_name<data_type>,
CONSTRAINT <table_name>_pk PRIMARY KEY (<column_name>)
)
Points To Remember :
 You can not alter any constraint , you need drop them and recreate if you really need any changes.
2) Foreign key constraints :
A foreign key is a way to enforce referential integrity within your SQL Server database. A foreign key means that
values in one table must also appear in another table.
The referenced table is called the parent table while the table with the foreign key is called the child table. The
foreign key in the child table will generally reference a primary key in the parent table.
Syntax :
Create Table <table_name> (<column_name><data_type>,
<column_name><data_type>,
<column_name<data_type>,
CONSTRAINT <table_name>_fk FOREIGN KEY (<column_name>)
REFERENCES <table_name> (<column_name>)
)
Points To Remember :
 The Primary Key and Foreign Key references will not work with Global and Local Temporary tables.
3) Check constraints :
A check constraint in SQL Server (Transact-SQL) allows you to specify a condition on each row in a table.
Syntax :
Create Table <table_name> (<column_name><data_type>,
<column_name><data_type>,
<column_name<data_type>,
CONSTRAINT chk_<name>
CHECK (column_namn <condition>)
)
Points To Remember :
 A check constraint can NOT be defined on a SQL View.
 The check constraint defined on a table must refer to only columns in that table. It can not refer to columns
in other tables.
 A check constraint can NOT include a Sub query.
Working with Sub queries : ** Not IN with NULL

In SQL Server, a subquery is a query within a query. You can create subqueries within your SQL statements.
These subqueries can reside in the WHERE clause, the FROM clause, or the SELECT clause.

Joins in SQL Server :


INNER JOIN
It is the most common type of join. SQL Server INNER JOINS return all rows from multiple tables where the join
condition is met.

Syntax :

SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column
LEFT OUTER JOIN
This type of join returns all rows from the LEFT-hand table specified in the ON condition and only those rows
from the other table where the joined fields are equal (join condition is met).

Syntax :

SELECT columns
FROM table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column;
RIGHT OUTER JOIN
This type of join returns all rows from the RIGHT-hand table specified in the ON condition and only those rows
from the other table where the joined fields are equal (join condition is met).

Syntax :

SELECT columns
FROM table1
RIGHT [OUTER] JOIN table2
ON table1.column = table2.column;;
FULL OUTER JOIN
This type of join returns all rows from the LEFT-hand table and RIGHT-hand table with nulls in place where the
join condition is not met.

Syntax :

SELECT columns
FROM table1
FULL [OUTER] JOIN table2
ON table1.column = table2.column;
SELF JOIN
A self join is a join in which a table is joined with itself (which is also called Unary relationships), specially when
the table has a FOREIGN KEY which references its own PRIMARY KEY. To join a table itself means that each row
of the table is combined with itself and with every other row of the table.
The self join can be viewed as a join of two copies of the same table. The table is not actually copied, but SQL
performs the command as though it were.
The syntax of the command for joining a table to itself is almost same as that for joining two different tables. To
distinguish the column names from one another, aliases for the actual the table name are used, since both the
tables have same name. Table name aliases are defined in the FROM clause of the SELECT statement. See the
syntax :

Syntax :

SELECT a.column_name, b.column_name,


FROM table1 a, table1 b
WHERE a.common_filed = b.common_field;
CTE (Common Table Expression) : ** CTE and TEMP assigned Table

The common table expression (CTE) is a temporary named result set that you can reference within a SELECT,
INSERT, UPDATE, or DELETE statement. You can also use a CTE in a CREATE VIEW statement, as part of the
view’s SELECT query. In addition, as of SQL Server 2008, you can add a CTE to the new MERGE statement.

Syntax :

[WITH <common_table_expression> [,...]]


<common_table_expression>::=
cte_name [(column_name [,...])]
AS (cte_query)

Types Of CTE :

Nonrecursive
Recursive
CASE WHEN CONDTION :
The CASE statement is SQL’s way of handling if/then logic. The CASE statement is followed by at least one pair of
WHEN and THEN statements—SQL’s equivalent of IF/THEN in Excel. It must end with the END statement. The ELSE
statement is optional, and provides a way to capture values not specified in the WHEN/THEN statements. CASE is
easiest to understand in the context syntax.

Syntax :

CASE expression
WHEN value_1 THEN result_1
WHEN value_2 THEN result_2
WHEN value_n THEN result_n
ELSE result
END

IF ELSE STATEMENT :
In SQL Server, you use a WHILE LOOP when you are not sure how many times you will execute the loop body and
the loop body may not execute even once.
Syntax :
IF condition
{...statements to execute when condition is TRUE...}
[ELSE
{...statements to execute when condition is FALSE...} ]
WHILE LOOP :
In SQL Server, you use a WHILE LOOP when you are not sure how many times you will execute the loop body and
the loop body may not execute even once.

Syntax :

WHILE condition
BEGIN
{...statements...}
END

VIEWS :
A VIEW, in essence, is a virtual table that does not physically exist in SQL Server. Rather, it is created by a query
joining one or more tables.

Syntax :

CREATE VIEW [schema_name.]view_name AS


[ WITH { ENCRYPTION | SCHEMABINDING | VIEW_METADATA }
SELECT expressions
FROM tables
[WHERE conditions];

POINTS TO REMEMBER :
PIVOT
PIVOT is one of the new relational operator introduced in Sql Server 2005. It provides an easy mechanism in Sql
Server to transform rows into columns.

Syntax :
SELECT <non-pivoted column>,
[first pivoted column] AS <column name>,
[second pivoted column] AS <column name>,
...
[last pivoted column] AS <column name>
FROM
(<SELECT query that produces the data>)
AS <alias for the source query>
PIVOT
(
<aggregation function>(<column being aggregated>)
FOR
[<column that contains the values that will become column headers>]
IN ( [first pivoted column], [second pivoted column],
... [last pivoted column])
) AS <alias for the pivot table>
<optional ORDER BY clause>;

POINTS TO REMEMBER :
 When aggregate functions are used with PIVOT, the presence of any null values in the value column are
not considered when computing an aggregation.
UNPIVOT
UNPIVOT is almost reversal of the PIVOT operation. It basically provides a mechanism for transforming columns
into rows.
Stored Procedures:
A stored procedure in SQL Server is a group of one or more Transact-SQL statements, its
stored in SQL Server. Storing the code inside the SQL Server object gives us many advantages.
• Reduced server/client network traffic
• Stronger security
• Reuse of code
• Easier maintenance
• Improved performance
Types:
• User-defined
• System
• Ex: SP_Helptext , sp_who2
• Extended User-Defined
• XP_fixeddrives
Stored Procedures:
Syntax:
1. Create:
Create Procedure Procedure-name
(
@ParameterName datatype , -- Input parameter
@ParameterName datatype out -- Output Parameters (If required)
)
As
Begin
Sql statement used in the stored procedure
End
2. Alter
Alter Procedure Procedure-name
(
@ParameterName datatype , -- Input parameter
@ParameterName datatype out -- Output Parameters (If required)
)
As
Begin
Sql statement used in the stored procedure
End
3. Drop
Stored Procedures:
Examples:

/* Getstudentname is the name of the stored procedure*/


Create PROCEDURE Getstudentname(
@studentid INT --Input parameter
)
AS
BEGIN
SELECT Firstname+' '+Lastname FROM tbl_Students WHERE studentid=@studentid
END

EXEC Getstudentname 1
Stored Procedures:
Examples:

/* GetstudentnameInOutputVariable is the name of the stored procedure which uses output variable
@Studentname to collect the student name returns by the stored procedure*/
Create PROCEDURE GetstudentnameInOutputVariable
(
@studentid INT, --Input parameter , Studentid of the student
@studentname VARCHAR(200) OUT -- Out parameter declared with the help of OUT keyword
)
AS
BEGIN
SELECT @studentname= Firstname+' '+Lastname FROM tbl_Students WHERE studentid=@studentid
END
Views:
Creates a virtual table whose contents (columns and rows) are
defined by a query. Use this statement to create a view of the data in one or more
tables in the database.

Purposes:
• To focus, simplify, and customize the perception each user has of the database.
• As a security mechanism by allowing users to access data through the view, without granting
the users permissions to directly access the underlying base tables.
• To provide a backward compatible interface to emulate a table whose schema has changed.
CURSOR :
Microsoft SQL Server statements produce a complete result set, but there are times when the results
are best processed one row at a time. Opening a cursor on a result set allows processing the result set one row
at a time.
Syntax:
DECLARE cursor_name CURSOR
[LOCAL | GLOBAL] --define cursor scope
[FORWARD_ONLY | SCROLL] --define cursor movements (forward/backward)
[STATIC | KEYSET | DYNAMIC | FAST_FORWARD] --basic type of cursor
[READ_ONLY | SCROLL_LOCKS | OPTIMISTIC] --define locks
FOR select_statement --define SQL Select statement
FOR UPDATE [col1,col2,...coln] --define columns that need to be updated

POINTS TO REMEMBER :
 You cannot use cursors or triggers on a table with a clustered columnstore index. This restriction does not
apply to nonclustered columnstore indexes; you can use cursors and triggers on a table with a nonclustered
index.
TRIGGERS :
A trigger is a special kind of a store procedure that executes in response to certain action on the table like
insertion, deletion or updating of data. It is a database object which is bound to a table and is executed
automatically. You can’t explicitly invoke triggers. The only way to do this is by performing the required action
no the table that they are assigned to.
Types Of Triggers
• After Triggers (For Triggers)
• Instead Of Triggers

Syntax:
CREATE [ OR ALTER ] TRIGGER [ schema_name . ]trigger_name
ON { table | view }
[ WITH <dml_trigger_option> [ ,...n ] ]
{ FOR | AFTER | INSTEAD OF }
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
[ WITH APPEND ]
[ NOT FOR REPLICATION ]
AS { sql_statement [ ; ] [ ,...n ] | EXTERNAL NAME <method specifier [ ; ] > }
FUNCTIONS :
Function is a database object in Sql Server. Basically it is a set of sql statements that accepts
only input parameters, perform actions and return the result. Function can return only single value or a table.
We can’t use function to Insert, Update, Delete records in the database table(s).
Types:
• System Defined Function
• User Defined Function

System Defined Function:


These functions are defined by Sql Server for different purpose. We have two types of system defined
function in Sql Server
1. Scalar Function – abs, rand, round, upper, lower, ltrim, convert.
2. Aggregate Function – max, min, avg, count.
User Defined Function:
These functions are created by user in system database or in user defined database. We
three types of user defined functions.
• Scalar Function - User defined scalar function also returns single value as a result of
actions perform by function. We return any datatype value from function.
• Inline Table Valued Function - User defined inline table-valued function returns a table
variable as a result of actions perform by function. The value of table variable should be
derived from a single SELECT statement.
• Multi-Statement Table-Valued Function - User defined multi-statement table-valued
function returns a table variable as a result of actions perform by function. In this a table
variable must be explicitly declared and defined whose value can be derived from a
multiple sql statements.
Syntax:
-- Transact-SQL Multi-Statement Table-Valued Function Syntax
CREATE [ OR ALTER ] FUNCTION [ schema_name. ] function_name
( [ { @parameter_name [ AS ] [ type_schema_name. ] parameter_data_type
[ = default ] [READONLY] }
[ ,...n ]
]
)
RETURNS @return_variable TABLE <table_type_definition>
[ WITH <function_option> [ ,...n ] ]
[ AS ]
BEGIN
function_body
RETURN
END
[;]
POINTS TO REMEMBER :
 User-defined functions cannot be used to perform actions that modify the database state.
 User-defined functions cannot contain an OUTPUT INTO clause that has a table as its target.
 User-defined functions can not return multiple result sets. Use a stored procedure if you need to
return multiple result sets.
 Error handling is restricted in a user-defined function. A UDF does not support TRY…CATCH,
@ERROR or RAISERROR.
 User-defined functions cannot call a stored procedure, but can call an extended stored procedure.
 User-defined functions cannot make use of dynamic SQL or temp tables. Table variables are
allowed.
 SET statements are not allowed in a user-defined function.
 The FOR XML clause is not allowed
Difference Between Function And Stored Procedure :
FOR XML
• A SELECT query returns results as a rowset. You can optionally retrieve formal results of a SQL
query as XML by specifying the FOR XML clause in the query. The FOR XML clause can be used in
top-level queries and in sub queries. The top-level FOR XML clause can be used only in the SELECT
statement. In sub queries, FOR XML can be used in the INSERT, UPDATE, and DELETE statements.
It can also be used in assignment statements.
In a FOR XML clause, you specify one of these modes:
• RAW
• AUTO
• EXPLICIT
• PATH
Syntax:
SELECT * FROM tablename
FOR XML AUTO
What is an execution plan :

The plan for a SQL statement is a set of instructions. This tells the database how to
access the data and join it together.

Plans come in two varieties:

Estimated
An estimated execution plan is generated without actually executing the
query. It is based on available statistics on indexes.

Actual
An actual execution plan is generated after executing the query. It is more
informative and reliable as it is based on actual execution not on estimated
statistics.
Estimated VS Actual :
Important operators of execution plan:
 Table scan
 Index seek
 Index scan
 RID Lookup
 Key lookup

Statistics IO:
Set statistics IO on
Table scan :
It looks each and every row at the table and bring out the
expected results from database tables.
Index scan :
It looks only the index at the table and bring out the expected
results from database tables.
Index seek :
It looks index and as well as the given inputs but completely
through the index.
OpenXML
• SQL Server 2000 provides a system-defined function, OpenXML, that creates Rowsets from XML
documents.
• OPENXML allows the data in XML document to be treated just like the columns and rows of your
database table
• The OPENXML function allows developers to parse XML data so that it can be stored as relational data in
tabular form. This function supports the XML data type and the sp_xml_preparedocument system
stored procedure accepts this new data type. This procedure is used by OPENXML function.
• Inserting from XML is faster when using openxml
• OPENXML provides an easy way to use an XML document as a data-source for your procedures.

POINTS TO REMEMBER :
 OPENXML is very memory intensive. The pointer returned by the system stored procedure
sp_xml_preparedocument is a memory pointer to a COM XML document object model. So, you must be careful
not to load very large XML documents into memory with OPENXML because it may overload your server's
memory.
OpenXML
Example:
DECLARE @h int
DECLARE @xmldoc VARCHAR(1000)
--xmldoc is set with the xml elements which are to be inserted into the table students with FirstName,
ID,Technology as table columns
SET @xmldoc =
'<root>
<student FirstName="Ravi" ID="1" Technology="DotNet"></student>
<student FirstName="Avdesh" ID="2" Technology="DotNet"></student> </root>'
EXEC sp_xml_preparedocument @h OUTPUT, @xmldoc
--This sp_xml_preparedocument is internal server SP (pseudo SP). which takes the xmldoc as input and
gives an output in @h which contains the data which is to be manipulated further
INSERT INTO student
SELECT * FROM OpenXML(@h,'/root/student')
WITH student
EXEC sp_xml_removedocument @h
--sp_xml_removedocument free's up the memory.
Transactions
A transaction is a single unit of work. If a transaction is successful, all of the data modifications
made during the transaction are committed and become a permanent part of the database. If a
transaction encounters errors and must be canceled or rolled back, then all of the data modifications
are erased.

SQL Server operates in the following transaction modes.


• Autocommit transactions
• Explicit transactions
• Implicit transactions
• Batch-scoped transactions

Syntax:
BEGIN { TRAN | TRANSACTION }
[ { transaction_name | @tran_name_variable }
[ WITH MARK [ 'description' ] ] ] [ ; ]
Index
• An index is an on-disk structure associated with a table or views that
speed retrieval of rows from the table or view. An index contains keys
built from one or more columns in the table or view. These keys are
stored in a structure (B-tree) that enables SQL Server to find the row
or rows associated with the key values quickly and efficiently.

Types:
1. Clustered
2. Non-Clustered
Clustered index
• Clustered indexes sort and store the data rows in the table or view
based on their key values. These are the columns included in the
index definition. There can be only one clustered index per table,
because the data rows themselves can be sorted in only one order.
• The only time the data rows in a table are stored in sorted order is
when the table contains a clustered index. When a table has a
clustered index, the table is called a clustered table. If a table has no
clustered index, its data rows are stored in an unordered structure
called a heap.
Syntax:
CREATE CLUSTERED INDEX Index Name ON Tablename (columnname)
Non-clustered index
• Nonclustered indexes have a structure separate from the data rows. A
nonclustered index contains the nonclustered index key values and each key
value entry has a pointer to the data row that contains the key value.
• The pointer from an index row in a nonclustered index to a data row is called
a row locator. The structure of the row locator depends on whether the data
pages are stored in a heap or a clustered table. For a heap, a row locator is a
pointer to the row. For a clustered table, the row locator is the clustered
index key.

Syntax:
CREATE NON CLUSTERED INDEX Index Name ON Tablename (columnname)
SQL Server Profiler
SQL Server Profiler is an interface to create and manage traces and analyze and
replay trace results. Events are saved in a trace file that can later be analyzed or used to
replay a specific series of steps when trying to diagnose a problem.

We can do the following using SQL Server Profiler:


• Create a trace
• Watch the trace results as the trace runs
• Store the trace results in a table
• Start, stop, pause, and modify the trace results as necessary
• Replay the trace results

Event & Event Class


Dynamic SQL Queries
In some applications having hard coded SQL statements is
not appealing, because of the dynamic nature of the queries being issued
against the database server. Because of this sometimes there is a need to
dynamically create a SQL statement on the fly and then run that
command.

SQL Server offers a few ways of running a dynamically built SQL


statement. These ways are:
• Writing a query with parameters
• Using EXEC
• Using sp_executesql
Import and Export wizards
SQL Server Import and Export Wizard is a simple way to copy data from a
source to a destination. This overview describes the data sources that the wizard can use
as sources and destinations, as well as the permissions you need to run the wizard.
Steps:
1. In SQL Server Management Studio, connect to an instance of the SQL Server
Database Engine.
2. Expand Databases.
3. Right-click a database.
4. Point to Tasks.
5. Click one of the following options.
• Import Data
• Export Data
Import and Export wizards
Import and Export wizards
7. Choose a Data Source
Import and Export wizards
Import and Export wizards
Import and Export wizards
Import and Export wizards
Import and Export wizards
Database backup
Database backup
Database backup
Database backup
Database backup
Example for using SQL Statement:
BACKUP DATABASE [AdventureWorks] TO
DISK = N'\\nas\Backup\L40\SQL2005\AdventureWorks_backup_200702120215.bak'
WITH NOFORMAT, NOINIT, NAME = N'AdventureWorks-Full Database Backup',
SKIP, NOREWIND, NOUNLOAD, STATS = 10
Database Restore
Database Restore
Database Restore
Database Restore
Database Restore
Example for using SQL Statement:
----Restore Database
RESTORE DATABASE YourDB
FROM DISK = 'D:\BackUpYourBaackUpFile.bak'
WITH MOVE 'YourMDFLogicalName' TO 'D:\DataYourMDFFile.mdf',
MOVE 'YourLDFLogicalName' TO 'D:\DataYourLDFFile.ldf‘
Database Detach and Attach
The data and transaction log files of a database can be
detached and then reattached to the same or another instance of SQL
Server. Detaching and attaching a database is useful if you want to
change the database to a different instance of SQL Server on the same
computer or to move the database.
Detach
Detaching a Database Using TSQL
Command
USE [master]
GO
ALTER DATABASE AdventureWorks
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
EXEC dbo.sp_detach_db @dbname = N'AdventureWorks',
@keepfulltextindexfile=N'true'
GO
Attach database
Attach database
Attaching a Database Using TSQL
USE [master]
GO
CREATE DATABASE [AdventureWorks] ON
( FILENAME = N'D:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\
MSSQL\DATA\AdventureWorks_Data.mdf' ),
( FILENAME = N'D:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\
MSSQL\DATA\AdventureWorks_Log.ldf' )
FOR ATTACH
GO
Generate scripts from database
Generate scripts from database
Generate scripts from database
Generate scripts from database
Generate scripts from database
Generate scripts from database
System tables
SQL SEVER SYSTEM TABLE (INSTANCE LEVEL SCOPED)
• syslogins
• sysdatabases
• sysservers
• sysperfinfo
• sysconfigures
• sysaltfiles
• Sysprocesses
• Syscacheobjects
SQL SERVER SYSTEM TABLES (DATABASE LEVEL SCOPED)
• sysusers
• sysobjects
• sysindexes
• fn_virtualfilestats
• sysdepends
System tables
SQL SERVER SYSTEM TABLES (INSIDE MSDB)
• suspect_pages
• sysjobs
• sysjobhistory
• backupset
• Restorehistory
System Stored procedure

• Sp_help
• sp_helpdb
• Sp_helptext
• Sp_depends
• sp_helpfile
• sp_spaceused
• sp_who
• sp_lock
• sp_configure
• sp_tables
• sp_columns
• sp_depends
Security
• Credentials
• Users
• Roles
Linked Servers
Linked Servers
Linked Servers
Linked Servers
Linked Servers
Linked Servers
Linked Servers
Linked Servers
Partitioned Tables and Indexes
SQL Server supports table and index partitioning. The data
of partitioned tables and indexes is divided into units that can be
spread across more than one filegroup in a database. The data is
partitioned horizontally, so that groups of rows are mapped into
individual partitions. All partitions of a single index or table must reside
in the same database. The table or index is treated as a single logical
entity when queries or updates are performed on the data.
Partitioned Tables
Database table partitioning is the process where very large tables are divided into multiple parts. The
data in partitioned tables is horizontally divided into units that can be spread across more than one filegroup
in a database.
Partitioning can make large tables more manageable and scalable. The main of goal of partitioning is to
aid in maintenance of large tables and to reduce the overall response time to read and load data for particular
SQL operations

• What is filegroup: Database objects and files can be grouped together in filegroups for allocation and
administration purposes. There are two types of filegroups:

• Primary file group: The primary filegroup contains the primary data file and any other files not specifically
assigned to another filegroup. All pages for the system tables are allocated in the primary filegroup.

• User-defined file group: User-defined filegroups are any filegroups that are specified by using the
FILEGROUP keyword in a CREATE DATABASE or ALTER DATABASE statement.
Partitioned Tables
Syntax:
USE AdventureWorks2012;
GO
-- Adds four new filegroups to the AdventureWorks2012 database
ALTER DATABASE AdventureWorks2012
ADD FILEGROUP test1fg;
GO
ALTER DATABASE AdventureWorks2012
ADD FILEGROUP test2fg;
GO
ALTER DATABASE AdventureWorks2012
ADD FILEGROUP test3fg;
GO
ALTER DATABASE AdventureWorks2012
Partitioned Tables
Syntax:

-- Adds one file for each filegroup.


ALTER DATABASE AdventureWorks2012
ADD FILE
(
NAME = test1dat1,
FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\
t1dat1.ndf',
SIZE = 5MB,
MAXSIZE = 100MB,
FILEGROWTH = 5MB
)
Partitioned Tables
Syntax:
ALTER DATABASE AdventureWorks2012
ADD FILE
(
NAME = test2dat2,
FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\
DATA\t2dat2.ndf',
SIZE = 5MB,
MAXSIZE = 100MB,
FILEGROWTH = 5MB
)
TO FILEGROUP test2fg;
GO
Partitioned Tables
Syntax:
ALTER DATABASE AdventureWorks2012
ADD FILE
(
NAME = test3dat3,
FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\
DATA\t3dat3.ndf',
SIZE = 5MB,
MAXSIZE = 100MB,
FILEGROWTH = 5MB
)
TO FILEGROUP test3fg;
GO
Partitioned Tables
Syntax:
ALTER DATABASE AdventureWorks2012
ADD FILE
(
NAME = test4dat4,
FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\
DATA\t4dat4.ndf',
SIZE = 5MB,
MAXSIZE = 100MB,
FILEGROWTH = 5MB
)
TO FILEGROUP test4fg;
GO
Partitioned Tables
Syntax:

-- Creates a partition function called myRangePF1 that will partition a table into four partitions
CREATE PARTITION FUNCTION myRangePF1 (int)
AS RANGE LEFT FOR VALUES (1, 100, 1000) ;
GO
-- Creates a partition scheme called myRangePS1 that applies myRangePF1 to the four filegroups created
above
CREATE PARTITION SCHEME myRangePS1
AS PARTITION myRangePF1
TO (test1fg, test2fg, test3fg, test4fg) ;
GO
-- Creates a partitioned table called PartitionTable that uses myRangePS1 to partition col1
CREATE TABLE PartitionTable (col1 int PRIMARY KEY, col2 char(10))
ON myRangePS1 (col1) ;
Partitioned Index
Syntax:
CREATE PARTITION FUNCTION PF(INT) AS RANGE FOR VALUES (0, 10, 100)
CREATE PARTITION SCHEME PS AS PARTITION PF ALL TO ([PRIMARY])

CREATE TABLE T1 (A INT, B INT)


CREATE CLUSTERED INDEX T1A ON T1(A) ON PS(A)
Maintenance plans
Maintenance plans
Maintenance plans
Maintenance plans
Maintenance plans
ER Diagram
Thank you

You might also like