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

SQL Concepts

Uploaded by

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

SQL Concepts

Uploaded by

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

Joins:

Joins are used to relate one or more tables in SQL Server. Joins are a part of a SQL Statement that
retrieves rows from a table or tables according to specified conditions.
Types of Joins

1. Inner Join
2. Outer Join
3. Cross Join
4. Self Join

First we create two tables on which we apply the joins.

Creation of the first table is as

1. create table emp(empId int, empName varchar(15))

Insertion of data into the table

1. insert into emp


2. select 1,'deepak'union all
3. select 2,'Arora'union all
4. Select 3,'raj'union all
5. select 4,'Mahi'union all
6. select 5,'daljeet'union all
7. select 6,'kiran'

Output

1. select * from emp

Creation of second table


1. create table emp_add(empId int, empAdd varchar(25))

insertion of data

1. select 1,'Lakser'union all


2. select 2,'haridwar'union all
3. select 3,'usa'union all
4. select 7,'canada'union all
5. select 8,'punjab'union all
6. select 9,'Chandigarh'

Output

1. select * from emp_add

1. Inner Join:

It return all the Rows that satisfy the join Condition. Inner join produces records that match in
Tables.

1. select e.empId,e.empName,e1.empAdd from emp e inner join emp_add e1 on e.empId=e1.e


mpId

Output
2. Outer Join:

There are three types of Outer Join

1. Left Outer Join


2. Right Outer Join
3. Full Outer Join

Left Outer Join

The result of the Left Outer Join contains all the records of the left table and if any record of the left
table does not match the right table than it returns Null for the right side table.

1. select e.empId,e.empName,e1.empAdd from emp e left outer join emp_add e1 on e.empId=


e1.empId

Output

Right Outer Join

The result of the Right Outer Join contains all the records of the right table and if any record of the
right table does not match the Left table than it returns Null for the left side table.

1. select e.empId,e.empName,e1.empAdd from emp e right outer join emp_add e1 on e.empId


=e1.empId
Output

Full Outer Join

A Full Outer Join fetches all records of both tables; where the record does not match, it returns Null.

1. select e.empId,e.empName,e1.empAdd from emp e full outer join emp_add e1 on e.empId=


e1.empId

Output

2. Cross Join:

This join is a Cartesian join. The result of a Cross Join contains records that are the multiplication of
the records from both tables.

1. select e.empId,e.empName,e1.empAdd from emp e cross join emp_add e1


Here I create a table to explain self join

1. create table emp_mngr(empName varchar(15),mngrName varchar(15))

Insertion of data

1. insert into emp_mngr


2. select 'ravi','Gaurav'union all
3. select'Gaurav','tom'union all
4. select 'sem','singh'union all
5. select 'singh','arora

Output

1. select * from emp_mngr

4. Self Join:

In the Self Join a table is joined to itself. A Self Join can be an Inner Join or Outer Join. In the given
example we find the employees that are the manager of other employees.

1. select e.empName,e.mngrName from emp_mngr e inner join emp_mngr e1 on e.empName


=e1.mngrName

Output
Constraints:
Constraints are rules and restrictions applied on a column or a table such that unwanted
data can't be inserted into tables. This ensures the accuracy and reliability of the data in the
database. We can create constraints on single or multiple columns of any table. Constraints
maintain the data integrity and accuracy in the table.

Constraints can be classified into the following two types.

Column Types Constraints

Definitions of these types of constraints is given when the table is created.

1. Create Table My_Constraint


2. (
3. IID int NOT NULL,
4. Salary int CHECK(Salary>5000)
5. )

Table Types Constraints

Definitions of these types of constraints is given after the creation of the table using the
Alter Command.

1. Alter Table My_Cosntraint


2. Add constraint Check_Constraint Check(Age>50)

SQL Server contains the following 6 types of constraints:

• Not Null Constraint


• Check Constraint
• Default Constraint
• Unique Constraint
• Primary Constraint
• Foreign Constraint

Let us understand each constraint briefly.

1. Not Null Constraint

A Not null constraint restrict the insertion of null values into a column. If we are using a Not Null
Constraint for a column then we cannot ignore the value of this column during an insert of data into
the table.
Column Level

Syntax

1. CREATE TABLE Table_Name


2. (
3. Column_Name Datatype CONSTRAINT Constraint_Name NOT NULL,
4. );

Table Level

Syntax

1. ALTER TABLE Table_Name


2. ALTER COLUMN Column_Name Datatype NOT NULL

Example

1. Alter Table My_Constraint


2. Alter Column IId int Not Null

2. Check Constraint

A Check constraint checks for a specific condition before inserting data into a table. If the
data passes all the Check constraints then the data will be inserted into the table otherwise
the data for insertion will be discarded. The CHECK constraint ensures that all values in a
column satisfies certain conditions.

Column Level

Syntax

1. Create Table Table_Name


2. (
3. Column_Name Datatype Constraint Constraint_Name Check(Condition)
4. )

Example

1. Create Table Constraint_


2. (
3. IId int Constraint Constraint_Name Check(IId>100)
4. )

Table Level

Syntax

1. Alter Table Table_Name


2. Add Constraint Constraint_Name Check(Condition)

Example

1. Alter table Constraint_

2. Add constraint Cons_Name Check(IId>150)

3. Default Constraint

Specifies a default value for when a value is not specified for this column. If in an insertion
query any value is not specified for this column then the default value will be inserted into
the column.

Column Level

Syntax

1. Create Table Table_Name


2. (
3. Column_Name DataType Constraint Constraint_Name Default(Value),
4. )

Example

1. Create Table My_Table1


2. (
3. IId int default(1500),
4. Name Nvarchar(50)Constraint Name_Default Default('Pankaj'),
5. Age Int,
6. Salary Int Default(100)
7. )
Table Level

Syntax

1. Alter Table Tabel_Name


2. Add Constraint Constraint_Name Default(Value) for[Column_Name]

Example

1. Alter Table My_Table1

2. Add Constraint cons_Default Default(40) for[Age]

4. Unique Constraint

It ensures that each row for a column must have a unique value. It is like a Primary key but
it can accept only one null value. In a table one or more column can contain a Unique
Constraint.

Column Level

Syntax

1. Create Table Table_Name


2. (
3. Column_Name Datatype Constraint Constraint_Name Unique
4. )

Example

1. Create Table MY_Tab


2. (
3. IId int constraint Unique_Cons Unique ,
4. Name nvarchar(50)
5. )

Table Level

Syntax

1. Alter Table_Name
2. Add Constraint Constraint_Name Unique(Column_Name)

Example

1. Alter Table My_Tab

2. Add Constraint Unique_Cons_ Unique(Name)

5. Primary Key Constraint

A Primary key uniquly identifies each row in a table. It cannot accept null and
duplicate data. One or more of the columns of a table can contain a Primary key.

Column Level

Syntax

1. Create Table Table_Name


2. (
3. Column_Name Datatype Constraint Constraint_Name Primary Key,
4. )

Example

1. Create Table Employee


2. (
3. IId int constraint Const_primary_IId primary key,
4. Name nvarchar(50)
5. )

Table Level

Syntax

1. Alter Table Table_Name


2. Add constraint Constraint_Name Primary Key(Column_Name)

Example

1. Alter Table Employee


2. Add constraint Constraint_Name Primary Key(IId)

6. Foreign Key Constraint

A Foreign Key is a field in a database table that is a Primary key in another table. A Foreign
key creates a relation between two tables. The first table contains a primary key and the
second table contains a foreign key.

Column Level

Syntax

1. Create Table Table_Name


2. (
3. Column_Name Datatype Constraint Constraint_Name References Reference_Tabl
e_Name(Reference_Column_Name)
4. )

Example

1. Create Table Employee_


2. (
3. IId int constraint Cons_Reference References My_Constraint(IId),
4. Age int,
5. Salary int
6. )

Table Level

ALTER TABLE Table_Name

1. ADD CONSTRAINT Constraint_Name FOREIGN KEY(Column_Name)


2. REFERENCES Reference_Table (Column_Name)

Example

1. ALTER TABLE Employee_

2. ADD CONSTRAINT Cons_Emp_Foreign FOREIGN KEY(IId)


3. REFERENCES My_Constraint(IId)
What are Majic Tables in SQL Server:
Whenever a trigger fires in response to the INSERT,DELETE,or UPDATE statement,two special tables are
created.These are the inserted and the deleted tables.They are also referred to as the magic tables.These are
the conceptual tables and are similar in structure to the table on which trigger is defined(the trigger table).

While using triggers these Inserted & Deleted tables (called as magic tables) will be created automatically.

The inserted table contains a copy of all records that are inserted in the trigger table.

The deleted table contains all records that have been deleted from deleted from the trigger table.

Whenever any updation takes place,the trigger uses both the inserted and deleted tables.

When we insert any record then that record will be added into this Inserted table initially, similarly while
updating a record a new entry will be inserted into Inserted table & old value will be inserted into Deleted
table. In the case of deletion of a record then it will insert that record into the Deleted table.

Note that the Magic Table does not contain the information about the columns of the data-type text, ntext, or
image. Attempting to access these columns will cause an error.

Views:
https://www.c-sharpcorner.com/UploadFile/f0b2ed/views-in-sql-server/
https://www.c-sharpcorner.com/article/sql-server-indexed-views/
https://www.codeproject.com/Articles/199058/SQL-Server-Indexed-Views-Speed-Up-Your-
Select-Quer
https://logicalread.com/advantages-indexed-views-sql-server-mc03/

Views are virtual tables that hold data from one or more tables. It is stored in the database. A view does
not contain any data itself, it is a set of queries that are applied to one or more tables that are stored
within the database as an object. Views are used for security purposes in databases. Views restrict the
user from viewing certain columns and rows. In other words, using a view we can apply the restriction
on accessing specific rows and columns for a specific user. A view can be created using the tables of the
same database or different databases. It is used to implement the security mechanism in the SQL Server.

The uses of views In SQL

Views are used to implement the security mechanism in SQL Server. Views are generally used to restrict
the user from viewing certain columns and rows. Views display only the data specified in the query, so it
shows only the data that is returned by the query defined during the creation of the view. The rest of the
data is totally abstract from the end user.
1. CREATE VIEW view_name AS
2. SELECT columns
3. FROM tables
4. WHERE conditions;

Drop View Employee_View1

Sp_Rename OldViewName , NewViewName

Alter View Employee_View4

Getting Information about a view: We can retrieve all the information of a view using the Sp_Helptext
system Stored Procedure. Let us see an example.

Sp_Helptext Employee_View4

sp_refreshview is a system-level Stored Procedure that refreshes the metadata of any view once you
edit the schema of the table. Let's execute the following:

We don't get the results we exepected because the schema of the view is already defined. So when we
add a new column into the table it will not change the schema of the view and the view will contain the
previous schema. For removing this problem we use the system-defined Stored Procedure
sp_refreshview.

SchemaBinding a VIEW

In the previous example we saw that if we add a new column into the table then we must refresh the
view.

Such a way if we change the data type of any column in a table then we should refresh the view. If we
want to prevent any type of change in a base table then we can use the concept of SCHEMABINDING. It
will lock the tables being referred to by the view and restrict all kinds of changes that may change the
table schema (no Alter command).

We can't specify "Select * from tablename" with the query. We need to specify all the column names for
reference.

1. Create View Employee_Details3


2. with SCHEMABINDING
3. as
4. select Emp_Id,Emp_Name,Emp_Salary,Emp_City from DBO.Employee_Details

Types of VIWES:
1. SIMPLE VIEW -----we can perform DML operations
2. COMPLEX VIEW -----we cannot perform DML operations but we can update view
3. Indexed View---with schema binding, we can create unique cluster index on
this, we cannot create constraints.
Disadvantages of views

• Performance: The DBMS the query against the view into queries against the underlying source table. If a
table is defined by a multi table query, then even a simple query against a view becomes a complicated
join, and it may take a long time to complete. This is reference to insert, delete and update operations
• Update restrictions: when a user tries to update rows of a view, the DBMS must translate the request
into an update into an update on rows of the underlying source table. This is possible for simple views,
but more complicated views cannot be updated.

Practice

CREATE VIEW VW_Employee


AS
SELECT * FROM Employee

1. We cannot create view on TEMPORARY TABLE

2. After creating a view if we insert any records in base table it will effect in the VIEW
After creating a view if we insert any records in VIEW it will effect in base table.
After creating a view if we delete any records in base table it will effect in the VIEW
After creating a view if we delete any records in VIEW it will effect in base table.
3. CREATE VIEW VW_dept_test
AS
SELECT * FROM dept_test

After creating a view if we add column in base table it won’t effect in VIEW. If we want see schema
changes we have to refresh the view.
Exec sp_refreshview VW_dept_test

4. After creating view if we drop table we cannot retive data from view
5. A normal view is just a saved query, nothing more. The data isn't saved on the disk--it isn't
materialized. Thus, you cannot have integrity constraints (check constraints, foreign keys, or
primary keys) on a view: there's nothing to constrain. Even an index view--which is
materialized--does not allow for constraints
6. We cannot create constraints, index on VIEWS

What is Indexed View

An indexed view has a unique clustered index. The unique clustered index is stored in SQL Server
and updated like any other clustered index. An indexed view is more significant compared to
standard views that involve complex processing of large numbers of rows, such as aggregating lots
of data, or joining many rows. If such views are frequently referenced in queries, we can improve
performance by creating a unique clustered index on the view. For standard view result set is not
stored in database, instead of this the result set is computed for each query but in case of clustered
index the result set is stored in the database just like a table with a clustered index is stored.
Queries that don’t specifically use the indexed view can even benefit from the existence of the
clustered index from the view. Index view has some cost in the form of performance, if we create an
indexed view, every time we modify data in the underlying tables then not only must SQL Server
maintain the index entries on those tables, but also the index entries on the view. In the developer
and enterprise editions of SQL Server, the optimizer can use the indexes of views to optimize
queries that do not specify the indexed view. In the other editions of SQL Server, however, the
query must include the indexed view and specify the hint NOEXPAND to get the benefit of the index
on the view.
Indexes:
https://www.sqlshack.com/what-is-the-difference-between-clustered-and-non-clustered-indexes-
in-sql-server/

Indexes are used to speed-up query process in SQL Server, resulting in high performance. They are
similar to textbook indexes. In textbooks, if you need to go to a particular chapter, you go to the index,
find the page number of the chapter and go directly to that page. Without indexes, the process of finding
your desired chapter would have been very slow.

The same applies to indexes in databases. Without indexes, a DBMS has to go through all the records in
the table in order to retrieve the desired results. This process is called table-scanning and is extremely
slow. On the other hand, if you create indexes, the database goes to that index first and then retrieves
the corresponding table records directly.

There are two types of Indexes in SQL Server:

1. Clustered Index
2. Non-Clustered Index

Clustered Index
A clustered index defines the order in which data is physically stored in a table. Table data can be sorted
in only way, therefore, there can be only one clustered index per table. In SQL Server, the primary key
constraint automatically creates a clustered index on that particular column.

Let’s take a look. First, create a “student” table inside “schooldb” by executing the following script, or
ensure that your database is fully backed up if you are using your live data:

CREATE DATABASE schooldb

CREATE TABLE student

id INT PRIMARY KEY,

name VARCHAR(50) NOT NULL,

gender VARCHAR(50) NOT NULL,


DOB datetime NOT NULL,

total_score INT NOT NULL,

city VARCHAR(50) NOT NULL

Notice here in the “student” table we have set primary key constraint on the “id” column. This
automatically creates a clustered index on the “id” column. To see all the indexes on a particular table
execute “sp_helpindex” stored procedure. This stored procedure accepts the name of the table as a
parameter and retrieves all the indexes of the table. The following query retrieves the indexes created
on student table.

EXECUTE sp_helpindex student

The above query will return this result:

index_name index_description index_keys

PK__student__3213E83F7F60ED59 clustered, unique, primary key located on PRIMARY id

In the output you can see the only one index. This is the index that was automatically created because of
the primary key constraint on the “id” column.

This clustered index stores the record in the student table in the ascending order of the “id”. Therefore, if
the inserted record has the id of 5, the record will be inserted in the 5th row of the table instead of the
first row. Similarly, if the fourth record has an id of 3, it will be inserted in the third row instead of the
fourth row. This is because the clustered index has to maintain the physical order of the stored records
according to the indexed column i.e. id. To see this ordering in action, execute the following script:

USE schooldb

INSERT INTO student

VALUES
(6, 'Kate', 'Female', '03-JAN-1985', 500, 'Liverpool'),

(2, 'Jon', 'Male', '02-FEB-1974', 545, 'Manchester'),

(9, 'Wise', 'Male', '11-NOV-1987', 499, 'Manchester'),

(3, 'Sara', 'Female', '07-MAR-1988', 600, 'Leeds'),

(1, 'Jolly', 'Female', '12-JUN-1989', 500, 'London'),

(4, 'Laura', 'Female', '22-DEC-1981', 400, 'Liverpool'),

(7, 'Joseph', 'Male', '09-APR-1982', 643, 'London'),

(5, 'Alan', 'Male', '29-JUL-1993', 500, 'London'),

(8, 'Mice', 'Male', '16-AUG-1974', 543, 'Liverpool'),

(10, 'Elis', 'Female', '28-OCT-1990', 400, 'Leeds');

The above script inserts ten records in the student table. Notice here the records are inserted in random
order of the values in the “id” column. But because of the default clustered index on the id column, the
records are physically stored in the ascending order of the values in the “id” column. Execute the
following SELECT statement to retrieve the records from the student table.

Non-Clustered Indexes
A non-clustered index doesn’t sort the physical data inside the table. In fact, a non-clustered index is
stored at one place and table data is stored in another place. This is similar to a textbook where the book
content is located in one place and the index is located in another. This allows for more than one non-
clustered index per table.

It is important to mention here that inside the table the data will be sorted by a clustered index.
However, inside the non-clustered index data is stored in the specified order. The index contains column
values on which the index is created and the address of the record that the column value belongs to.

When a query is issued against a column on which the index is created, the database will first go to the
index and look for the address of the corresponding row in the table. It will then go to that row address
and fetch other column values. It is due to this additional step that non-clustered indexes are slower
than clustered indexes.

Creating a Non-Clustered Index

The syntax for creating a non-clustered index is similar to that of clustered index. However, in case of
non-clustered index keyword “NONCLUSTERED” is used instead of “CLUSTERED”. Take a look at the
following script.

CREATE NONCLUSTERED INDEX IX_tblStudent_Name


ON student(name ASC)
The above script creates a non-clustered index on the “name” column of the student table. The index
sorts by name in ascending order. As we said earlier, the table data and index will be stored in different
places. The table records will be sorted by a clustered index if there is one. The index will be sorted
according to its definition and will be stored separately from the table.

Performance Tuning:
https://www.c-sharpcorner.com/article/sql-server-performance-tuning-tips/

Database is the most important and powerful part of any application. If your database is
not working properly and taking long time to compute the result, this means something is
going wrong in database. Here, database tune up is required, otherwise performance of the
application will degrade.

I know a lot of articles already published on this topic. But in this article, I tried to provide a
list of database tune up tips that will cover all the aspects of database. Database tuning is a
very critical and fussy process. It is true that database tuning is a database admin task but
we should have the basic level of knowledge for doing this. Because, if we are working on a
project where there is no role of admin, then it is our responsibility to the maintain the
performance of the database. If performance of database is degraded, then it will cause
worst effect on the whole system. In this article, I will explain some basic database tuning
tips that I learned from my experience and from my friends who are working as database
administrator. Using these tips, you can maintain or upgrade the performance of your
database system. Basically, these tips are written for SQL Server but we can implement
these into another databases too, like Oracle and MySQL. Please read these tips carefully
and at the end of article, let me know if you find something wrong or incorrect.

Avoid Null value in fixed length field

We should avoid the Null value in fixed length fields because if we insert the NULL value in
a fixed length field, then it will take the same amount of space as the desired input value for
that field. So, if we require a null value in a field, then we should use a variable length field
that takes lesser space for NULL. The use of NULLs in a database can reduce the database
performance, especially, in WHERE clauses. For example, try to use varchar instead of char
and nvarchar.

1. Never use Select * Statement:

When we require all the columns of a table, we usually use a “Select *” statement. Well, this
is not a good approach because when we use the “select *” statement, the SQL Server
converts * into all column names before executing the query, which takes extra time and
efforts. So, always provide all the column names in the query instead of “select *”.

Normalize tables in database

Normalized and managed tables increase the performance of a database. So, always try to
perform at least 3rd normal form. It is not necessary that all tables requires 3NF
normalization form, but if any table contains 3NF form normalization, then it can be called
well structured tables.

Keep Clustered Index Small

Clustered index stores data physically into memory. If the size of a clustered index is very
large, then it can reduce the performance. Hence, a large clustered index on a table with a
large number of rows increases the size significantly. Never use an index for frequently
changed data because when any change in the table occurs, the index is also modified, and
that can degrade performance.

Use Appropriate Data type

If we select inappropriate data type, it will reduce the space and enhance the performance;
otherwise, it generates the worst effect. So, select an appropriate data type according to the
requirement. SQL contains many data types that can store the same type of data but you
should select an appropriate data type because each data type has some limitations and
advantages upon another one.

Store image path instead of image itself

I found that many developers try to store the image into database instead of the image
path. It may be possible that it is requirement of application to store images into database.
But generally, we should use image path, because storing image into database increases the
database size and reduces the performance.

USE Common Table Expressions (CTEs) instead of Temp table

We should prefer a CTE over the temp table because temp tables are stored physically in a
TempDB which is deleted after the session ends. While CTEs are created within memory.
Execution of a CTE is very fast as compared to the temp tables and very lightweight too.

Use Appropriate Naming Convention

The main goal of adopting a naming convention for database objects is to make it easily
identifiable by the users, its type, and purpose of all objects contained in the database. A
good naming convention decreases the time required in searching for an object. A good
name clearly indicates the action name of any object that it will perform.

1. * tblEmployees // Name of table


2. * vw_ProductDetails // Name of View
3. * PK_Employees // Name of Primary Key

Use UNION ALL instead of UNION

We should prefer UNION ALL instead of UNION because UNION always performs sorting
that increases the time. Also, UNION can't work with text datatype because text datatype
doesn't support sorting. So, in that case, UNION can't be used. Thus, always prefer UNION
All.

Use Small data type for Index

It is very important to use Small data type for index . Because, the bigger size of data type
reduces the performance of Index. For example, nvarhcar(10) uses 20 bytes of data and
varchar(10) uses 10 bytes of the data. So, the index for varhcar data type works better. We
can also take another example of datetime and int. Datetime data type takes 8 Bytes and int
takes 4 bytes. Small datatype means less I/O overhead that increases the performance of
the index.

1. Use Count(1) instead of Count(*) and Count(Column_Name):

There is no difference in the performance of these three expressions; but, the last two
expressions are not good considered to be a good practice. So, always use count(10) to get
the numbers of records from a table.

Use Stored Procedure

Instead of using the row query, we should use the stored procedure because stored
procedures are fast and easy to maintain for security and large queries.
Use Between instead of In

If Between can be used instead of IN, then always prefer Between. For example, you are
searching for an employee whose id is either 101, 102, 103 or 104. Then, you can write the
query using the In operator like this:

1. Select * From Employee Where EmpId In (101,102,103,104)

You can also use Between operator for the same query.

1. Select * from Employee Where EmpId Between 101 And 104

Use If Exists to determine the record

It has been seen many times that developers use "Select Count(*)" to get the existence of
records. For example

1. Declare @Count int;


2. Set @Count=(Select * From Employee Where EmpName Like '%Pan%')
3. If @Count>0
4. Begin
5. //Statement
6. End

But, this is not a proper way for such type of queries. Because, the above query
performs the complete table scan, so you can use If Exists for same query. That will
increase the performance of your query, as below.

1. IF Exists(Select Emp_Name From Employee Where EmpName Like '%Pan%')


2. Begin
3. //Statements
4. End

Never Use ” Sp_” for User Define Stored Procedure

Most programmers use “sp_” for user-defined Stored Procedures. I suggest to never use
“sp_” for user-defined Stored Procedure because in SQL Server, the master database has a
Stored Procedure with the "sp_" prefix. So, when we create a Stored Procedure with the
"sp_" prefix, the SQL Server always looks first in the Master database, then in the user-
defined database, which takes some extra time.

Practice to use Schema Name

A schema is the organization or structure for a database. We can define a schema as a


collection of database objects that are owned by a single principal and form a single
namespace. Schema name helps the SQL Server finding that object in a specific schema. It
increases the speed of the query execution. For example, try to use [dbo] before the table
name.

Avoid Cursors

A cursor is a temporary work area created in the system memory when a SQL statement is
executed. A cursor is a set of rows together with a pointer that identifies the current row. It
is a database object to retrieve the data from a result set one row at a time. But, use of a
cursor is not good because it takes long time because it fetches data row by row. So, we can
use a replacement of cursors. A temporary table for or While loop may be a replacement of
a cursor in some case.

SET NOCOUNT ON

When an INSERT, UPDATE, DELETE or SELECT command is executed, the SQL Server
returns the number affected by the query. It is not good to return the number of rows
affected by the query. We can stop this by using NOCOUNT ON.

Use Try–Catch

In T-SQL, a Try-Catch block is very important for exception handling. A best practice and
use of a Try-Catch block in SQL can save our data from undesired changes. We can put all T-
SQL statements in a TRY BLOCK and the code for exception handling can be put into a
CATCH block.

Remove Unused Index

Remove all unused indexes because indexes are always updated when the table is updated
so the index must be maintained even if not used.

Always create index on table

An index is a data structure to retrieve fast data. Indexes are special lookup tables that the
database search engine can use to speed up data retrieval. Simply an index is a pointer to
data in a table. Mainly an index increases the speed of data retrieval. So always try to keep
minimum one index on each table it may be either clustered or non-clustered index.

Use Foreign Key with appropriate action

A foreign key is a column or combination of columns that is the same as the primary key,
but in a different table. Foreign keys are used to define a relationship and enforce integrity
between two tables. In addition to protecting the integrity of our data, FK constraints also
help document the relationships between our tables within the database itself. Also define
a action rules for delete and update command , you can select any action among the No
Action, Set NULL, Cascade and set default.
Use Alias Name

Aliasing renames a table or a column temporarily by giving another name. The use of table
aliases means to rename a table in a specific SQL statement. Using aliasing, we can provide
a small name to large name that will save our time.

Use Transaction Management

A transaction is a unit of work performed against the database. A transaction is a set of


work (T-SQL statements) that execute together like a single unit in a specific logical order
as a single unit. If all the statements are executed successfully then the transaction is
complete and the transaction is committed and the data will be saved in the database
permanently. If any single statement fails then the entire transaction will fail and then the
complete transaction is either cancelled or rolled back.

Use Index Name in Query

Although in most cases the query optimizer will pick the appropriate index for a specific
table based on statistics, sometimes it is better to specify the index name in your SELECT
query.

Example

1. SELECT
2. e.Emp_IId,
3. e.First_Name,
4. e.Last_Name
5. FROM dbo.EMPLOYEE e
6. WITH (INDEX (Clus_Index))
7. WHERE e.Emp_IId > 5
8. Select Limited Data

We should retrieve only the required data and ignore the unimportant data. The less data
retrieved, the faster the query will run. Rather than filtering on the client, push as much
filtering as possible on the server-end. This will result in less data being sent on the wire
and you will see results much faster.

Drop Index before Bulk Insertion of Data

We should drop the index before insertion of a large amount of data. This makes the insert
statement run faster. Once the inserts are completed, you can recreate the index again.

Use Unique Constraint and Check Constraint

A Check constraint checks for a specific condition before inserting data into a table. If the
data passes all the Check constraints then the data will be inserted into the table otherwise
the data for insertion will be discarded. The CHECK constraint ensures that all values in a
column satisfies certain conditions.

A Unique Constraint ensures that each row for a column must have a unique value. It is like
a Primary key but it can accept only one null value. In a table one or more column can
contain a Unique Constraint. So we should use a Check Constraint and Unique Constraint
because it maintains the integrity in the database.

Importance of Column Order in index

If we are creating a Non-Clustered index on more than one column then we should consider
the sequence of the columns. The order or position of a column in an index also plays a vital
role in improving SQL query performance. An index can help to improve the SQL query
performance if the criteria of the query matches the columns that are left most in the index
key. So we should place the most selective column at left most side of a non-clustered
index.

Recompiled Stored Procedure

We all know that Stored Procedures execute T-SQL statements in less time than the similar
set of T-SQL statements are executed individually. The reason is that the query execution
plan for the Stored Procedures are already stored in the "sys.procedures" system-defined
view. We all know that recompilation of a Stored Procedure reduces SQL performance. But
in some cases it requires recompilation of the Stored Procedure. Dropping and altering of a
column, index and/or trigger of a table. Updating the statistics used by the execution plan
of the Stored Procedure. Altering the procedure will cause the SQL Server to create a new
execution plan.

Use Sparse Column

Sparse column provide better performance for NULL and Zero data. If you have any column
that contain large amount numbers of NULL and Zero then prefer Sparse Column instead of
default column of SQL Server. Sparse column take lesser space then regular column
(without SPARSE clause).

Example

1. Create Table Table_Name


2. (
3. Id int, //Default Column
4. Group_Id int Sparse // Sparse Column
5. )

Avoid Loops In Coding


Suppose you want to insert 10 of records into table then instead of using a loop to insert
the data into table you can insert all data using single insert query.

1. declare @int int;


2. set @int=1;
3. while @int<=10
4. begin
5. Insert Into Tab values(@int,'Value'+@int);
6. set @int=@int+1;
7. end

Above method is not a good approach to insert the multiple records instead of this you can
use another method like below.

1. Insert Into Tab values(1,'Value1'),(2,'Value2'),(3,'Value3'),(4,'Value4'),(5,'Value5'),


(6,'Value6'),(7,'Value7'),(8,'Value8'),(9,'Value9'),(10,'Value10');

Avoid Correlated Queries

In A Correlated query inner query take input from outer(parent) query, this query run for
each row that reduce the performance of database.

1. Select Name, City, (Select Company_Name


2. from
3. Company where companyId=cs.CustomerId) from Customer cs

The best method is that wehsould be prefer the join instaed of correlated query as below.

1. Select cs.Name, cs.City, co.Company_Name


2. from Customer cs
3. Join
4. Company co
5. on
6. cs.CustomerId=co.CustomerId

Avoid index and join hints

In some cases, index and join hint may be increase the performance of database, but if you
provide any join or index hint then server always try to use the hint provided by you
although it have a better execution plan, so such type of approach may be reduce the
database performance. Use Join or index hint if you are confidence that there is not any
better execution plan. If you have any doubt then make server free to choose a execution
plan.

Avoid Use of Temp table


Avoid use of temp table as much as you can because temp table is created into temp
database like any basic table structure. After completion of the task, we require to drop the
temp table. That rises the load on database. You can prefer the table variable instead of this.

Use Index for required columns

Index should be created for all columns which are using Where, Group By, Order By, Top,
and Distinct command.

Don't use Index for following condition

It is true that use of index makes the fast retrieval of the result. But, it is not always true. In
some cases, the use of index doesn't affect the performance of the query. In such cases, we
can avoid the use of index.

1. When size of table is very small.


2. Index is not used in query optimizer
3. DML(insert, Update, Delete) operation are frequent used.
4. Column contain TEXT, nText type of data.

Use View for complex queries

If you are using join on two or more tables and the result of queries is frequently used, then
it will be better to make a View that will contain the result of the complex query. Now, you
can use this View multiple times, so that you don't have to execute the query multiple times
to get the same result.

Use Full-text Index

If your query contains multiple wild card searches using LIKE(%%), then use of Full-text
Index can increase the performance. Full-text queries can include simple words and
phrases or multiple forms of a word or phrase. A full-text query returns any document that
contains at least one match (also known as a hit). A match occurs when a target document
contains all the terms specified in the Full-text query, and meets any other search
conditions, such as the distance between the matching terms.

Temporary Tables:
https://www.c-sharpcorner.com/UploadFile/f0b2ed/temporary-tables-in-sql-server/
These tables are automatically destroyed at the termination of the procedure or session that created
them. SQL Server provides the concept of temporary table that helps the developer in a great way.
These tables can be created at runtime and can do many kinds of operations that a normal table can do.
In SQL Server all temporary tables are present in the tempdb database.

Types of Temporary Tables

SQL Server contains the following two types of Temporary tables.

1. Local Temporary Tables


2. Global Temporary Tables

Local Temporary Tables:

Local temporary tables are temporary tables that are available only to the session that created them.
These tables are automatically destroyed at the termination of the procedure or session that created
them. Local temp tables are only available to the current connection for the user. Names of Local temp
tables starts with (“#”) hash sign.

Global Temporary Tables

Global temporary tables are temporary tables that are available to all sessions and all users. Once this
table has been created by a connection, like a permanent table then it is available to any user by any
connection. They are dropped automatically when the last session using the temporary table has
completed. Names of global temp tables start with (“##”) double hash sign.

Practice:

We can create stored procedure on TEMP table.

We can create constraints on TEMP table

alter table #Employee add constraintchk1check(salary>=1000)

We cannot create VIEW on TEMP table

We can create index on TEMP table create index i1 on #Employee(deptid)


When to use temporary tables?

1. To hold data for further query.


2. When we have a complex joins operation.
3. In some cases it may be a replacement of cursors.

Difference between subquery and derived table:


https://www.c-sharpcorner.com/article/difference-among-cte-derived-table-temp-table-sub-query/

Subquery Derived
Subqueries must be enclosed within Derived table must be enclosed within parentheses and table name
parentheses. must be provided.
Subquery can have only one column. Derived table can have one or more column.
Subquery mainly use in where clause. Derived table used in from clause.

Difference b/w Temp table and Temp variable:

Temp Table TempVariable


Scope of Temp Table is wider the temp variables of. Local temporary
Scope of the Temp variables are
tables are temporary tables that are available only to the session that
limited up to current batch and
created them and Global temporary tables are temporary tables that are
current stored procedure.
available to all sessions and all users.
Temp variables only through
Temp tables can be create using Create Table and Select Into commands Declare command can’t be created
using select into command.
We can not drop a Temp variables
Temp tables can be drop through Drop Command. but we can use truncate command
for temp variables.
Name of a temp variables can have
Name of Temp table can have maximum 116 characters.
MAXIMUM 128 characters.
Temp variable doesn’t support
Temp table support foreign key concept.
foreign key.
Temp variables doesn’t support
Temp tables support transaction management. transaction management. Rollback
not work for temp variables.
Temp variables are suitable with
Temp tables can easily handle large amount of data.
small amount of data.

Difference b/w CTE and Derived table:


CTE Derived Table
A CTE can be referenced multiple times in the same Derived table can’t referenced multiple times.
query. So CTE can use in recursive query. Derived table can’t use in recursive queries.
CTE are better structured compare to Derived table. Derived table’s structure is not good as CTE.

Difference b/w Temp table and Table variable:

1. SYNTAX

Below is the sample example of Creating a Below is the sample example of Declaring a

Temporary Table, Inserting re cords into it, Table Variable, Inserting records into it and

retrieving the rows from it and then finally dropping retrieving the rows from it.

the created Temporary Table.


-- Create Table Variable
DECLARE @Customer TABLE
-- Create Temporary Table (
CREATE TABLE #Customer Id INT,
(Id INT, Name VARCHAR(50)) Name VARCHAR(50)
--Insert Two records )
INSERT INTO #Customer --Insert Two records
VALUES(1,'Basavaraj') INSERT INTO @Customer
INSERT INTO #Customer VALUES(1,'Basavaraj')
VALUES(2,'Kalpana') INSERT INTO @Customer
--Reterive the records VALUES(2,'Kalpana')
SELECT * FROM #Customer --Reterive the records
--DROP Temporary Table SELECT * FROM @Customer
DROP TABLE #Customer GO
GO
RESULT:

2. MODIFYING STRUCTURE

Temporary Table structure can be changed after it’s Table Variables doesn’t support DDL

creation it implies we can use DDL statements statements like ALTER, CREATE, DROP etc,

ALTER, CREATE, DROP. implies we can’t modify the structure of Table

Below script creates a Temporary Table #Customer, variable nor we can drop it explicitly.

adds Address column to it and finally the Temporary

Table is dropped.

--Create Temporary Table


CREATE TABLE #Customer
(Id INT, Name VARCHAR(50))
GO
--Add Address Column
ALTER TABLE #Customer
ADD Address VARCHAR(400)
GO
--DROP Temporary Table
DROP TABLE #Customer
GO

3. STORAGE LOCATION

One of the most common MYTH about Temporary Table & Table Variable is that: Temporary Tables

are created in TempDB and Table Variables are created In-Memory. Fact is that both are created in

TempDB, below Demos prove this reality.

4. TRANSACTIONS

Temporary Tables honor the explicit transactions Table variables doesn’t participate in the

defined by the user. explicit transactions defined by the user.

5. USER DEFINED FUNCTION


Temporary Tables are not allowed in User Defined Table Variables can be used in User Defined

Functions. Functions.

6. INDEXES

Temporary table supports adding Indexes explicitly Table Variables doesn’t allow the explicit

after Temporary Table creation and it can also have addition of Indexes after it’s declaration, the

the implicit Indexes which are the result of Primary only means is the implicit indexes which are

and Unique Key constraint. created as a result of the Primary Key or

Unique Key constraint defined during Table

Variable declaration.

Difference b/w Temp table and CTE:

CTEs...
• Are unindexable (but can use existing indexes on referenced objects)
• Cannot have constraints
• Are essentially disposable VIEWs
• Persist only until the next query is run
• Can be recursive
• Do not have dedicated stats (rely on stats on the underlying objects)
#Temp Tables...
• Are real materialized tables that exist in tempdb
• Can be indexed
• Can have constraints
• Persist for the life of the current CONNECTION
• Can be referenced by other queries or subprocedures
• Have dedicated stats generated by the engine

Difference between Sql Server Char and Varchar Data Type

http://sqlhints.com/tag/temporary-table-vs-table-variable/
Everyone knows about the basic difference between CHAR and VARCHAR data types. In this
article apart from the basic difference, will discuss on one more interesting difference which
I have observed recently.

CHAR Data Type is a Fixed Length Data Type. For example if you declare a variable/column
of CHAR (10) data type, then it will always take 10 bytes irrespective of whether you are
storing 1 character or 10 character in this variable or column. And in this example as we have
declared this variable/column as CHAR(10), so we can store max 10 characters in this
column.

On the other hand VARCHAR is a variable length Data Type. For example if you declare a
variable/column of VARCHAR (10) data type, it will take the no. of bytes equal to the number of
characters stored in this column. So, in this variable/column if you are storing only one character
then it will take only one byte and if we are storing 10 characters then it will take 10 bytes. And in
this example as we have declared this variable/column as VARCHAR (10), so we can store max 10
characters in this column.
VARCHAR(N)---8000 bytes----8KB VARCHAR(MAX)----2 GB
NVARCHAR will read different languages and It will occupy 2bytes for 1 char

Stored Procedure:
Stored Procedure: Stored Procedure in SQL Server can be defined as the set of logical group of SQL
statements which are grouped to perform a specific task. There are many benefits of using a stored
procedure. The main benefit of using a stored procedure is that it increases the performance of the
database.The other benefits of using the Stored Procedure are given below.

Benefits of Using the Stored Procedure


1. One of the main benefits of using the Stored procedure is that it reduces the amount of information sent
to the database server. It can become a more important benefit when the bandwidth of the network is
less. Since if we send the SQL query (statement) which is executing in a loop to the server through
network and the network gets disconnected, then the execution of the SQL statement doesn't return the
expected results, if the SQL query is not used between Transaction statement and rollback statement is
not used.
2. Compilation step is required only once when the stored procedure is created. Then after it does not
require recompilation before executing unless it is modified and reutilizes the same execution plan
whereas the SQL statements need to be compiled every time whenever it is sent for execution even if we
send the same SQL statement every time.
3. It helps in re usability of the SQL code because it can be used by multiple users and by multiple clients
since we need to just call the stored procedure instead of writing the same SQL statement every time. It
helps in reducing the development time.
4. Stored procedure is helpful in enhancing the security since we can grant permission to the user for
executing the Stored procedure instead of giving permission on the tables used in the Stored procedure.
5. Sometimes, it is useful to use the database for storing the business logic in the form of stored procedure
since it makes it secure and if any change is needed in the business logic, then we may only need to make
changes in the stored procedure and not in the files contained on the web server.

https://www.c-sharpcorner.com/article/how-to-create-a-stored-procedure-in-sql-server-
management-studio/

1. CREATE PROCEDURE stpInsertMember


2. @MemberName varchar(50),
3. @MemberCity varchar(25),
4. @MemberPhone varchar(15)
5.
6. AS
7. BEGIN
8. -- SET NOCOUNT ON added to prevent extra result sets from
9. -- interfering with SELECT statements.
10. SET NOCOUNT ON;
11.
12. Insert into tblMembers (MemberName,MemberCity,MemberPhone)
13. Values (@MemberName,@MemberCity, @MemberPhone)
14.
15. END
16. GO

17. Create PROCEDURE GetstudentnameInOutputVariable


18. (
19.
20. @studentid INT, --Input parameter , Studentid of the student
21. @studentname VARCHAR(200) OUT -- Out parameter declared with the help of OUT keyword
22. )
23. AS
24. BEGIN
25. SELECT @studentname= Firstname+' '+Lastname FROM tbl_Students WHERE studentid=@studentid
26. END

Alter PROCEDURE GetstudentnameInOutputVariable


(

@studentid INT, --Input parameter , Studentid of the student


@studentname VARCHAR (200) OUT, -- Output parameter to collect the student name
@StudentEmail VARCHAR (200)OUT -- Output Parameter to collect the student email
)
AS
BEGIN
SELECT @studentname= Firstname+' '+Lastname,
@StudentEmail=email FROM tbl_Students WHERE studentid=@studentid
END
Execute Getstudentname 1

Functions:
1. UDFs support modular programming. Once you create a UDF and store it in a database then you
can call it any number of times. You can modify the UDF independent of the source code.
2. UDFs reduce the compilation cost of T-SQL code by caching plans and reusing them for repeated
execution.
3. They can reduce network traffic. If you want to filter data based on some complex constraints
then that can be expressed as a UDF. Then you can use this UDF in a WHERE clause to filter data.

Types of UDF

1. Scalar Functions
2. Table Valued Functions

Consider the following Student and Subject tables for examples.

1. Scalar Functions

A Scalar UDF accepts zero or more parameters and return a single value. The return type of a scalar
function is any data type except text, ntext, image, cursor and timestamp. Scalar functions can be use in a
WHERE clause of the SQL Query.

Crating Scalar Function

To create a scalar function the following syntax is used.

Example

Create a function as follows.

1. CREATE FUNCTION GetStudent(@Rno INT)


2. RETURNS VARCHAR(50)
3. AS
4. BEGIN
5. RETURN (SELECT Name FROM Student WHERE Rno=@Rno)
6. END

To execute this function use the following command.

1. PRINT dbo.GetStudent(1)

Output: Ram
1. Table Valued Functions

A Table Valued UDF accepts zero or more parameters and return a table variable. This type of function is
special because it returns a table that you can query the results of a join with other tables. A Table
Valued function is further categorized into an “Inline Table Valued Function” and a “Multi-Statement
Table Valued Function”.

A. Inline Table Valued Function

An Inline Table Valued Function contains a single statement that must be a SELECT statement. The
result of the query becomes the return value of the function. There is no need for a BEGIN-END block in
an Inline function.

Crating Inline Table Valued Function

Create function fnGetEmployee()

1. returns Table
2. As
3. return (Select * from Employee)

1. --Now call the above created function


2. Select * from fnGetEmployee()

B. Multi-Statement Table Valued Function

A Multi-Statement contains multiple SQL statements enclosed in BEGIN-END blocks. In the function
body you can read data from databases and do some operations. In a Multi-Statement Table valued
function the return value is declared as a table variable and includes the full structure of the table to be
returned. The RETURN statement is without a value and the declared table variable is returned.

Crating Multi-Statement Table Valued Function

To create a scalar function the following syntax is used.

1. Create function fnGetMulEmployee()


2. returns @Emp Table
3. (
4. EmpID int,
5. FirstName varchar(50),
6. Salary int
7. )
8. As
9. begin
10. Insert into @Emp Select e.EmpID,e.FirstName,e.Salary from Employee e;
11. --Now update salary of first employee
12. update @Emp set Salary=25000 where EmpID=1;
13. --It will update only in @Emp table not in Original Employee table
14. return
15. end

Select * from fnGetMulEmployee()

Difference between Stored Procedure and User Defined Function:

l. User Defined function Stored Procedure

No.

1 Function must return a value. Stored procedure may or not return values.

2 Will allow only Select statement, it will not Can have select statements as well as DML

allow us to use DML statements. statements such as insert, update, delete

etc

3 It will allow only input parameters, doesn’t It can have both input and output parameters.

support output parameters.

4 It will not allow us to use try-catch blocks. For exception handling we can use try catch

blocks.

5 Transactions are not allowed within Can use transactions within Stored procefures.

functions.
6 We can use only table variables, it will not Can use both table variables aswell as

allow using temporary tables. temporary table in it.

7 Stored procedures can’t be called from Stored Procedures can call functions.

function.

8 Functions can be called from select Procedures can’t be called from

statement. Select/Where/Having etc statements.

Execute/Exec

statement can be used to call/execute stored

procedure.

9 UDF can be used in join clause as a result Procedures can’t be use

set.
CURSORS:
https://www.dotnettricks.com/learn/sqlserver/sql-server-different-types-of-cursors

Introduction

A cursor is a database object that points to a result set. We use cursor to fetch any specific row from result set.
Most of time cursor is used by application programmer.

Implementation of cursor in SQL

• We can implement cursor through standard database APIs.


• We can implement cursor through Transact-SQL

SQL Statement used in cursor

• DECLARE : It is used to define a new cursor.


• OPEN : It is used to open a cursor
• FETCH : It is used to retrieve a row from a cursor.
• CLOSE : It is used to close a cursor.
• DEALLOCATE : It is used to delete a cursor and releases all resources used by cursor.

There are four type of cursor

• Dynamic cursor
• Keyset cursor
• Static cursor
• Forward-only cursor

Dynamic Cursor

Dynamic cursor is scrollable and sensitive to database changes.

Keyset_cursor

Keyset_cursor is scrollable and sensitive to database changes for update and delete but not for insertion.

Static cursor

Static cursor is scrollable but not sensitive to database changes.

Forward_only
Forward_only is not scrollable but sensitive to database changes.

SQL SERVER – Examples of Cursors


1. CREATE TABLE Employee
2. (
3. EmpID int PRIMARY KEY,
4. EmpName varchar (50) NOT NULL,
5. Salary int NOT NULL,
6. Address varchar (200) NOT NULL,
7. )
8. GO
9. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(1,'Mohan',12000,'Noida')
10. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(2,'Pavan',25000,'Delhi')
11. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(3,'Amit',22000,'Dehradun')
12. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(4,'Sonu',22000,'Noida')
13. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(5,'Deepak',28000,'Gurgaon')
14. GO
15. SELECT * FROM Employee

Static Cursor - Example


1. SET NOCOUNT ON
2. DECLARE @Id int
3. DECLARE @name varchar(50)
4. DECLARE @salary int
5. DECLARE cur_emp CURSOR
6. STATIC FOR
7. SELECT EmpID,EmpName,Salary from Employee
8. OPEN cur_emp
9. IF @@CURSOR_ROWS > 0
10. BEGIN
11. FETCH NEXT FROM cur_emp INTO @Id,@name,@salary
12. WHILE @@Fetch_status = 0
13. BEGIN
14. PRINT 'ID : '+ convert(varchar(20),@Id)+', Name : '+@name+ ', Salary : '+convert(varchar(20),@salary)
15. FETCH NEXT FROM cur_emp INTO @Id,@name,@salary
16. END
17. END
18. CLOSE cur_emp
19. DEALLOCATE cur_emp
20. SET NOCOUNT OFF
Dynamic Cursor - Example
1. --Dynamic Cursor for Update
2. SET NOCOUNT ON
3. DECLARE @Id int
4. DECLARE @name varchar(50)
5. DECLARE Dynamic_cur_empupdate CURSOR
6. DYNAMIC
7. FOR
8. SELECT EmpID,EmpName from Employee ORDER BY EmpName
9. OPEN Dynamic_cur_empupdate
10. IF @@CURSOR_ROWS > 0
11. BEGIN
12. FETCH NEXT FROM Dynamic_cur_empupdate INTO @Id,@name
13. WHILE @@Fetch_status = 0
14. BEGIN
15. IF @name='Mohan'
16. Update Employee SET Salary=15000 WHERE CURRENT OF Dynamic_cur_empupdate
17. FETCH NEXT FROM Dynamic_cur_empupdate INTO @Id,@name
18. END
19. END
20. CLOSE Dynamic_cur_empupdate
21. DEALLOCATE Dynamic_cur_empupdate
22. SET NOCOUNT OFF
23. Go
24. Select * from Employee

1. -- Dynamic Cursor for DELETE


2. SET NOCOUNT ON
3. DECLARE @Id int
4. DECLARE @name varchar(50)
5. DECLARE Dynamic_cur_empdelete CURSOR
6. DYNAMIC
7. FOR
8. SELECT EmpID,EmpName from Employee ORDER BY EmpName
9. OPEN Dynamic_cur_empdelete
10. IF @@CURSOR_ROWS > 0
11. BEGIN
12. FETCH NEXT FROM Dynamic_cur_empdelete INTO @Id,@name
13. WHILE @@Fetch_status = 0
14. BEGIN
15. IF @name='Deepak'
16. DELETE Employee WHERE CURRENT OF Dynamic_cur_empdelete
17. FETCH NEXT FROM Dynamic_cur_empdelete INTO @Id,@name
18. END
19. END
20. CLOSE Dynamic_cur_empdelete
21. DEALLOCATE Dynamic_cur_empdelete
22. SET NOCOUNT OFF
23. Go
24. Select * from Employee

Forward Only Cursor - Example


1. --Forward Only Cursor for Update
2. SET NOCOUNT ON
3. DECLARE @Id int
4. DECLARE @name varchar(50)
5. DECLARE Forward_cur_empupdate CURSOR
6. FORWARD_ONLY
7. FOR
8. SELECT EmpID,EmpName from Employee ORDER BY EmpName
9. OPEN Forward_cur_empupdate
10. IF @@CURSOR_ROWS > 0
11. BEGIN
12. FETCH NEXT FROM Forward_cur_empupdate INTO @Id,@name
13. WHILE @@Fetch_status = 0
14. BEGIN
15. IF @name='Amit'
16. Update Employee SET Salary=24000 WHERE CURRENT OF Forward_cur_empupdate
17. FETCH NEXT FROM Forward_cur_empupdate INTO @Id,@name
18. END
19. END
20. CLOSE Forward_cur_empupdate
21. DEALLOCATE Forward_cur_empupdate
22. SET NOCOUNT OFF
23. Go
24. Select * from Employee
1. -- Forward Only Cursor for Delete
2. SET NOCOUNT ON
3. DECLARE @Id int
4. DECLARE @name varchar(50)
5. DECLARE Forward_cur_empdelete CURSOR
6. FORWARD_ONLY
7. FOR
8. SELECT EmpID,EmpName from Employee ORDER BY EmpName
9. OPEN Forward_cur_empdelete
10. IF @@CURSOR_ROWS > 0
11. BEGIN
12. FETCH NEXT FROM Forward_cur_empdelete INTO @Id,@name
13. WHILE @@Fetch_status = 0
14. BEGIN
15. IF @name='Sonu'
16. DELETE Employee WHERE CURRENT OF Forward_cur_empdelete
17. FETCH NEXT FROM Forward_cur_empdelete INTO @Id,@name
18. END
19. END
20. CLOSE Forward_cur_empdelete
21. DEALLOCATE Forward_cur_empdelete
22. SET NOCOUNT OFF
23. Go
24. Select * from Employee

Keyset Driven Cursor - Example


1. -- Keyset driven Cursor for Update
2. SET NOCOUNT ON
3. DECLARE @Id int
4. DECLARE @name varchar(50)
5. DECLARE Keyset_cur_empupdate CURSOR
6. KEYSET
7. FOR
8. SELECT EmpID,EmpName from Employee ORDER BY EmpName
9. OPEN Keyset_cur_empupdate
10. IF @@CURSOR_ROWS > 0
11. BEGIN
12. FETCH NEXT FROM Keyset_cur_empupdate INTO @Id,@name
13. WHILE @@Fetch_status = 0
14. BEGIN
15. IF @name='Pavan'
16. Update Employee SET Salary=27000 WHERE CURRENT OF Keyset_cur_empupdate
17. FETCH NEXT FROM Keyset_cur_empupdate INTO @Id,@name
18. END
19. END
20. CLOSE Keyset_cur_empupdate
21. DEALLOCATE Keyset_cur_empupdate
22. SET NOCOUNT OFF
23. Go
24. Select * from Employee

1. -- Keyse Driven Cursor for Delete


2. SET NOCOUNT ON
3. DECLARE @Id int
4. DECLARE @name varchar(50)
5. DECLARE Keyset_cur_empdelete CURSOR
6. KEYSET
7. FOR
8. SELECT EmpID,EmpName from Employee ORDER BY EmpName
9. OPEN Keyset_cur_empdelete
10. IF @@CURSOR_ROWS > 0
11. BEGIN
12. FETCH NEXT FROM Keyset_cur_empdelete INTO @Id,@name
13. WHILE @@Fetch_status = 0
14. BEGIN
15. IF @name='Amit'
16. DELETE Employee WHERE CURRENT OF Keyset_cur_empdelete
17. FETCH NEXT FROM Keyset_cur_empdelete INTO @Id,@name
18. END
19. END
20. CLOSE Keyset_cur_empdelete
21. DEALLOCATE Keyset_cur_empdelete
22. SET NOCOUNT OFF
23. Go Select * from Employee

Read More Articles Related to SQL Server


Triggers:
http://sqltechi.blogspot.com/2012/11/sql-server-different-types-of-cursors.html

Triggers are database object. Basically these are special type of stored procedure that are automatically
fired/executed when a DDL or DML command statement related with the trigger is executed. Triggers are used
to assess/evaluate data before or after data modification using DDL and DML statements. These are also used
to preserve data integrity, to control server operations, to audit a server and to implement business logic or
business rule.

Types of Triggers

In Sql Server we can create four types of triggers Data Definition Language (DDL) triggers, Data Manipulation
Language (DML) triggers, CLR triggers and Logon triggers.

1. DDL Triggers
In SQL Server we can create triggers on DDL statements (like CREATE, ALTER, and DROP) and certain system
defined stored procedures that perform DDL-like operations.

Example : If you are going to execute the CREATE LOGIN statement or the sp_addlogin stored procedure to
create login user, then both these can execute/fire a DDL trigger that you can create on CREATE_LOGIN event
of Sql Server.

We can use only FOR/AFTER clause in DDL triggers not INSTEAD OF clause means we can make only
After Trigger on DDL statements.

DDL trigger can be used to observe and control actions performed on the server, and to audit these
operations. DDL triggers can be used to manage administrator tasks such as auditing and regulating database
operations.
2. DML Triggers
In SQL Server we can create triggers on DML statements (like INSERT, UPDATE, and DELETE) and stored
procedures that perform DML-like operations. DML Triggers are of two types

1. After Trigger (using FOR/AFTER CLAUSE)


This type of trigger fires after SQL Server finish the execution of the action successfully that fired it.

Example : If you insert record/row in a table then the trigger related/associated with the insert event on
this table will fire only after the row passes all the constraints, like as primary key constraint, and some
rules. If the record/row insertion fails, SQL Server will not fire the After Trigger.

2. Instead of Trigger (using INSTEAD OF CLAUSE)


This type of trigger fires before SQL Server starts the execution of the action that fired it. This is differ from
the AFTER trigger, which fires after the action that caused it to fire. We can have an INSTEAD OF
insert/update/delete trigger on a table that successfully executed but does not include the actual
insert/update/delete to the table.

Example : If you insert record/row in a table then the trigger related/associated with the insert event on
this table will fire before the row passes all the constraints, such as primary key constraint and some rules.
If the record/row insertion fails, SQL Server will fire the Instead of Trigger.

If we try to update a view that is based on multiple tables then it will throw an error in such cases
we can use this trigger.

CREATE TRIGGER trgAfterInsert ON [dbo].[Employee_Test]


FOR INSERT
AS
declare @empid int;
declare @empname varchar(100);
declare @empsal decimal(10,2);
declare @audit_action varchar(100);

select @empid=i.Emp_ID from inserted i;


select @empname=i.Emp_Name from inserted i;
select @empsal=i.Emp_Sal from inserted i;
set @audit_action='Inserted Record -- After Insert Trigger.';

insert into Employee_Test_Audit


(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values(@empid,@empname,@empsal,@audit_action,getdate());

PRINT 'AFTER INSERT trigger fired.'


GO

CREATE TRIGGER trgInsteadOfDelete ON [dbo].[Employee_Test]


INSTEAD OF DELETE
AS
declare @emp_id int;
declare @emp_name varchar(100);
declare @emp_sal int;

select @emp_id=d.Emp_ID from deleted d;


select @emp_name=d.Emp_Name from deleted d;
select @emp_sal=d.Emp_Sal from deleted d;

BEGIN
if(@emp_sal>1200)
begin
RAISERROR('Cannot delete where salary > 1200',16,1);
ROLLBACK;
end
else
begin
delete from Employee_Test where Emp_ID=@emp_id;
COMMIT;
insert into Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values(@emp_id,@emp_name,@emp_sal,'Deleted -- Instead Of Delete Trigger.',getdate());
PRINT 'Record Deleted -- Instead Of Delete Trigger.'
end
END
GO

IDENTITY:
https://www.c-sharpcorner.com/UploadFile/219d4d/identity-column-in-sql-server/
A SQL Server IDENTITY column is a special type of column that is used to automatically generate
key values based on a provided seed (starting point) and increment
IDENTITY(1,1)

The first parameter is the seed (from where the value will start) and the second parameter is the
increment value.

1. @@IDENTITY
2. SCOPE_IDENTITY
3. IDENT_CURRENT

@@IDENTITY: Returns the last identity values that were generated in a table in the
current session. This method is not limited to a specific scope.

SCOPE_IDENTITY: Returns the last identity values that are generated in any table in the
current session. This method returns values inserted only within the current scope.

IDENT_CURRENT: Returns the last identity value generated for a specific table in any session and
any scope. This method is not affected by scope and session, it only depends on a specific table.
Synthax: IDENT_CURRENT(Tablename)

IDENT_SEED: It returns the seed value of IDENTITY column, default is 1.


IDENT_INCR: It returns the increment value of IDENTITY column, default is 1.
We have 10 records in a table and we have deleted all 10 records and we are inserting new records
into a table, but it will take it as a 11 record to reseed identity column we need to use DBCC check.
To reseed an Identity column write and execute the following query:
DBCC CHECKIDENT ('iden1',RESEED,0)

set identity_insert iden1 off

IDENTITY_INSERT ON allows a user to insert data into an Identity column and


IDENTITY_INSERT OFF restricts a user from inserting data into an Identity column.

OFFSET FETCH:
The OFFSET and FETCH clauses are the options of the ORDER BY clause. They allow you to limit
the number of rows to be returned by a query.
The following illustrates the syntax of the OFFSET and FETCH clauses:
1 ORDER BY column_list [ASC |DESC]
2 OFFSET offset_row_count {ROW | ROWS}
3 FETCH {FIRST | NEXT} fetch_row_count {ROW | ROWS} ONLY
In this syntax:

• The OFFSET clause specifies the number of rows to skip before starting to return rows
from the query. The offset_row_count can be a constant, variable, or parameter that is
greater or equal to zero.
• The FETCH clause specifies the number of rows to return after the OFFSET clause has
been processed. The offset_row_count can a constant, variable or scalar that is greater or
equal to one.
• The OFFSET clause is mandatory while the FETCH clause is optional. Also,
the FIRST and NEXT are synonyms respectively so you can use them interchangeably.
Similarly, you can use the FIRST and NEXT interchangeably.

SELECT Fname, Lname


FROM Employee
ORDER BY Salary
OFFSET 2 ROWS---------roes to skip
FETCH NEXT 4 ROWS ONLY;
Merge:
Microsoft introduced the Merge statement in SQL Server 2008 to perform INSERT, DELETE,
and UPDATE in a single statement. The SQL MERGE Statement is used to modify the data
present in a target table based on data in source table.

-- SQL Server Merge Statement example


MERGE [Merge Table] AS mrg
USING (SELECT * FROM [Employee Table]) AS emp
ON mrg.Id = emp.Id
WHEN MATCHED AND mrg.[YearlyIncome] <= 50000 THEN DELETE
WHEN MATCHED AND mrg.[YearlyIncome] >= 80000 THEN
UPDATE SET mrg.[YearlyIncome] = mrg.[YearlyIncome] + 35000
WHEN NOT MATCHED THEN
INSERT ([FirstName]
,[LastName]
,[Education]
,[Occupation]
,[YearlyIncome]
,[Sales]
,[HireDate])
VALUES(emp.[FirstName]
,emp.[LastName]
,emp.[Education]
,emp.[Occupation]
,emp.[YearlyIncome]
,emp.[Sales]
,emp.[HireDate]);
GO

You might also like