SQL Server Notes_Updated (1)
SQL Server Notes_Updated (1)
3) PRINT –
4)IF() & IF() ELSE Conditions- Using this statements we can give
conditions to the program. For example - If I want only salary >
10000 Employee list.
Systax 1-
IF(x>y)
BEGIN
END
Systax 2-
IF(x>y)
BEGIN
END
ELSE
BEGIN
END
Syntax-
WHILE(val<10)
BEGIN
Val++
END
6) CONVERT(Datatype, value)-
1) Factorial.
2) DECLARE @a INT =0
3) DECLARE @b VARCHAR(MAX)= 'it''sstirng'
4) DECLARE @fact INT =1
5) SET @a=10
6)
7) WHILE(@a>=1)
8) BEGIN
9) PRINT @a
10) SET @fact=@fact*@a
11) SET @a-=1
12) END
13) PRINT @fact
2) Prime Number.
4) T-SQL - Transaction
1) DDL -
Eg
CREATETABLE FirstTable
(
Id int,
Name varchar(50),
Salary decimal(10,2),
IsActive bit,
Class char(1)
)
Guideline for creation of tables:
1) Table name should start with an alphabet.
2) Table name – blank space and single quotes not allowed.
3) Reserve words of that DBMS cannot be used as table name.
4) Proper datatype and size should be specified.
5) Unique column name should be specified.
B) Column Constraints –
1) NOT NULL – Usingthese constraints we can restrict null in
the particular column.
2) UNIQUE – It is use to define column as a unique. It does not
accept duplicate value. It can be null. We can have multiple
UNIQUE columns in the single table. It can be used as a
reference key in another table.
3) PRIMARY KEY – Once columns defined as primary key; it
does not allow duplicate values in the table. It cannot accept
null value. We can have only 1 primary keys in single table in
SQL server. It can be used as a reference key in another
table.
4) CHECK- It is use to give the condition to the column while
entering data in the table.
5) DEFAULT – It is use to set default value to particular column.
6) REFERENCES/Foreign key –We can use one table primary key
as a reference key in another table. It can be null. It must be
primary key/Unique key in another table.
C) ON DELETE CASCADE – Using these optionswhenever parent rows
is deleted in the referenced table then all corresponding child
rows are deleted from referencing table. This constraint is a form
of referential integrity constraints.
Example –
CREATETABLE Product(
Pno intPRIMARYKEY,
Pname varchar(100)UNIQUE,
Qno intDEFAULT(100),
Class char(1)NOTNULL,
Rate numeric(10,2)NOTNULL,
CHECK((Class='A'and Rate<1000)OR(class='B'and
Rate>1000 and Rate < 4500))
)
ON DELETE CASCADE
);
It’s use for modification for existing structure of the table in the
following situation.
Syntax:
-------------------------------------------------------------------------
2) DML-
A) SELECT Statement –
Use to retrieve data from tables.
i) Using Arithmetic operator-
Eg. – SELECT Ename, Sal, Sal+300 From Emp;
Eg.
C) UPDATE Command –
UPDATE <table name>
SET <col>=<val>
WHERE <Condi>
D) DELETE Command-
Syntax –
DELETE FROM <tblnm> where <condition>.
E)
3) DATA CONTROL - DCL
1) Create new user -
CREATELOGINNewAdminNameWITH PASSWORD = 'ABCD'
GO
Eg.
CREATELOGIN Aalim WITHPASSWORD='mansuri123'
GO
Eg.
UseYourDatabase;
GO
IFNOTEXISTS(SELECT*FROMsys.database_principalsWHERE name
=N'NewAdminName')
BEGIN
CREATEUSER[NewAdminName]FOR LOGIN [NewAdminName]
EXECsp_addrolememberN'db_owner',N'NewAdminName'
END;
GO
2) Grant –
It’s provide database access to usesr.
Syntax –
GRANTSELECT,INSERT,UPDATEON Product TO Aalim
GRANTSELECT,INSERTON dbo.YourTable2 TO YourUserName
GRANTSELECT,DELETEON dbo.YourTable3 TO YourUserName
3) User Maping–
Assigning Database to users.
4 .Joins in sql server, Inner Join,CrossJoin,Left Outer Join,Equi join, Right
Outer Join, Full Outer Join
Description:
In SQL joins are used to get data from two or more tables based on relationship between
some of the columns in tables. In most of the cases we will use primary key of first table
and foreign key of secondary table to get data from tables.By using this relationship, we can
reduce the duplication of data in every table.
Before enter into Joins concept first design two tables in database and enter data like as
shown below
Create one table with primary key and give name as “UserDetails”
After that create another table with Foreign Key and give name as OrderDetails
1 543224 1
2 213424 2
3 977776 3
4 323233 3
5 998756 1
Here OrderID is the Primary key and UserID is the foreign key in OrderDetails table.
SQL contains different types of Joins we will see each concept with example by using
above tables.
Types of Joins
1) Inner Joins
2) Outer Joins
3) Self Join
Inner Join
The join that displays onlythe rows that have a match in both the joined tables is
known as inner join. This is default join in the query and view Designer.
SELECT t1.column_name,t2.column_name
FROM table_name1 t1
ON t1.column_name=t2.column_name
Example
SELECT u.UserName,u.LastName,o.OrderNo
FROM UserDetails u
ON u.UserID=o.UserID
We can write our inner join query like this also it will give same result
SELECT u.UserName,u.LastName,o.OrderNo
FROM UserDetails u
JOIN OrderDetails o
ON u.UserID=o.UserID
Based on above result we can say that INNER JOIN keyword return rows when there is at
least one match in both tables. If there are rows in "UserDetails" that do not have
matches in "OrderDetails", those rows will NOT be listed.
1) Equi Join
3) Cross Join
Equi Join
The Equi join is used to display all the matched records from the joined tables and also
display redundant values. In this join we need to use * sign to join the table.
ON t1.column_name=t2.column_name
Example
SELECT *
FROM UserDetails u
INNER JOIN OrderDetails o
ON u.UserID=o.UserID
PrasanthiDo
2 Prasanthi Donthi 2 213424 2
nthi
MaheshDasa
3 Mahesh Dasari 3 977776 3
ri
MaheshDasa
3 Mahesh Dasari 4 323233 3
ri
In equi join we need to use only equality comparisons in the join relation. If we use other
operators such as (<,>) for our comparison condition then our Joins disqualifies for equi
join.
Natural Joins
The Natural join is same as our Equi join but only the difference is it will restrict to display
redundant values.
Example
SELECT *
FROM UserDetails
Note: These NATURAL Joins won’t work in our SQL Server (only supports in Oracle) it will
throw syntax error. If you observe above code "NATURAL" is not highlighted, indicating
that it is not recognized as a keyword.
Cross Join
A cross join that produces Cartesian product of the tables that involved in the join. The
size of a Cartesian product is the number of the rows in first table multiplied by the
number of rows in the second table.
Example
Or
PrasanthiDon
2 Prasanthi Donthi 1 543224 1
thi
PrasanthiDon
2 Prasanthi Donthi 2 213424 2
thi
PrasanthiDon
2 Prasanthi Donthi 3 977776 3
thi
PrasanthiDon
2 Prasanthi Donthi 4 323233 3
thi
PrasanthiDon
2 Prasanthi Donthi 5 998756 1
thi
MaheshDasa
3 Mahesh Dasari 1 543224 1
ri
MaheshDasa
3 Mahesh Dasari 2 213424 2
ri
MaheshDasa
3 Mahesh Dasari 3 977776 3
ri
MaheshDasa
3 Mahesh Dasari 4 323233 3
ri
MaheshDasa
3 Mahesh Dasari 5 998756 1
ri
Outer Joins
A join that returns all the rows that satisfy the condition and unmatched rows in the
joined table is an Outer Join.
The left outer join displays all the rows from the first table and matched rows from the
second table.
Syntax for Left Outer Join
ON t1.column_name=t2.column_name
Example
SELECT u.UserID,u.UserName,o.OrderNo
FROM UserDetails u
ON u.UserID=o.UserID
1 SureshDasari 543224
1 SureshDasari 998756
2 PrasanthiDonthi 213424
3 MaheshDasari 977776
3 MaheshDasari 323233
The right outer join displays all the rows from the second table and matched rows from
the first table.
Example
SELECT u.UserID,u.UserName,o.OrderNo
FROM UserDetails u
ON u.UserID=o.UserID
1 SureshDasari 543224
2 PrasanthiDonthi 213424
3 MaheshDasari 977776
3 MaheshDasari 323233
1 SureshDasari 998756
Full Outer Join displays all the matching and non matching rows of both the tables.
ON t1.column_name=t2.column_name
Example
SELECT u.UserID,u.UserName,o.OrderNo
FROM UserDetails u
ON u.UserID=o.UserID
SureshDas 54322
1 Suresh Dasari 1 1
ari 4
SureshDas 99875
1 Suresh Dasari 5 1
ari 6
MaheshDa 97777
3 Mahesh Dasari 3 3
sari 6
MaheshDa 32323
3 Mahesh Dasari 4 3
sari 3
Self Join
Joining the table itself called self-join. Self-join is used to retrieve the records having
some relation or similarity with other records in the same table. Here we need to use
aliases for the same table to set a self-join between single table and retrieve records
satisfying the condition in where clause.
To implement self join first design table and give a name as “EmployeeDetails”
1 Suresh 2
2 Prasanthi 4
3 Mahesh 2
4 Sai 1
5 Nagaraju 1
6 Mahendra 3
7 Sanjay 3
Now I want to get manager names of particular employee for that we need to write query
like this
on e1.EmpID=e2.EmpMgrID
Here if you observe above query EmployeeDetails table joined itself using table aliases
e1 and e2.
EmpName Manger
Sai Suresh
Nagaraju Suresh
Suresh Prasanthi
Mahesh Prasanthi
Mahendra Mahesh
Sanjay Mahesh
Prasanthi Sai
VIEWS
Types of View
View is a database object which is use to fetch data from the database.
It only shows the data to user.
1. System View
2. User Define View
1. Simple View
2. Complex view
Simple View
1.create view v1
2.as
3.select * from emp
Insertion
Updating
Renaming
1.exec sp_helptext v1
1.drop view v1
2. Complex view
3. Views created on more than one table are called Complex View.
We cannot perform all DML operations of a table on a Complex
View.
After having created a SQL Sequence, you can get the number
value from your created sequence using the NEXT VALUE FOR
function. The NEXT VALUE FOR will return the next sequential
number, the same as in the above screenshot.
We can also alter and drop the existing sequence. We can alter the
increment, cycle, minimum value and maximum value of a sequence.
Start with cannot be used with the alter statement.
ALTER SEQUENCE TableNextId
INCREMENT BY 2
MINVALUE 1000
MAXVALUE 100000
INDEXES
An Index is a database object that can be created on one or more
columns (16 max column combinations). When creating the index, it will
read the column(s) and forms a relevant data structure to minimize the
number of data comparisons. The index will improve the performance of
data retrieval and add some overhead to the data modification such as
create, delete and modify. So, it depends on how much data retrieval
can be done on table versus how much of DML (Insert, Delete and
Update) operations.
In short
An index is basically used for fast data retrieval from the database.
Type of Index
In a SQL Server database there are mainly the following two types of
indexes:
1.CREATE
CLUSTERED/NONCLUSTERED INDEX index_name ON table_
name(column nm);
Clustered Index
Eg.
Non-Clustered Index
CREATENONCLUSTEREDINDEX NONCI_PC ON
SALES(ProductCode);
The DROP INDEX Command
An index can be dropped using the SQL DROP command. Care should
be taken when dropping an index because performance may be
degraded or improved.
A synonym is nothing but a name. It does not store any data or any T-
SQL Query. It just refers to the database objects. Here the database
objects include the following:
Once a synonym is created we can use that synonym for what it stands
for, in other words in the preceding we created the synonym for the EMP
table. In this case we can use T-SQL statements like SELECT, INSERT,
UPDATE and DELETE.
Inside a table, a column often contains many duplicate values; and sometimes you only want to list the
different (distinct) values.
The SELECT DISTINCT statement is used to return only distinct (different) values.
The AND and OR operators are used to filter records based on more than one condition:
The AND operator displays a record if all the conditions separated by AND is TRUE.
The OR operator displays a record if any of the conditions separated by OR is TRUE.
AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending
order, use the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
If a field in a table is optional, it is possible to insert a new record or update a record without adding a value to
this field. Then, the field will be saved with a NULL value.
We will have to use the IS NULL and IS NOT NULL operators instead.
IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
The SELECT TOP clause is useful on large tables with thousands of records. Returning a large number of records
can impact on performance.
Note: Not all database systems support the SELECT TOP clause. MySQL supports the LIMIT clause to select a
limited number of records, while Oracle uses ROWNUM.
The MAX() function returns the largest value of the selected column.
MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
There are two wildcards used in conjunction with the LIKE operator:
Note: MS Access uses a question mark (?) instead of the underscore (_).
The percent sign and the underscore can also be used in combinations!
LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Tip: You can also combine any number of conditions using AND or OR operators.
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
WHERE CustomerName LIKE '%a' Finds any values that ends with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position
WHERE CustomerName LIKE 'a_%_%' Finds any values that starts with "a" and are at least 3 characters in length
WHERE ContactName LIKE 'a%o' Finds any values that starts with "a" and ends with "o"
Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
Try it Yourself »
The following SQL statement selects all customers with a CustomerName ending with "a":
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';
Try it Yourself »
The following SQL statement selects all customers with a CustomerName that have "or" in any position:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
Try it Yourself »
The following SQL statement selects all customers with a CustomerName that have "r" in the second position:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';
Try it Yourself »
The following SQL statement selects all customers with a CustomerName that starts with "a" and are at least 3
characters in length:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a_%_%';
Try it Yourself »
The following SQL statement selects all customers with a ContactName that starts with "a" and ends with "o":
Example
SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';
Try it Yourself »
The following SQL statement selects all customers with a CustomerName that NOT starts with "a":
Example
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';
Wildcard characters are used with the SQL LIKE operator. The LIKE operator is used in a WHERE clause to
search for a specified pattern in a column.
There are two wildcards used in conjunction with the LIKE operator:
Note: MS Access uses a question mark (?) instead of the underscore (_).
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
WHERE CustomerName LIKE 'a%' Finds any values that starts with "a"
WHERE CustomerName LIKE '%a' Finds any values that ends with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position
WHERE CustomerName LIKE 'a_%_%' Finds any values that starts with "a" and are at least 3 characters in length
WHERE ContactName LIKE 'a%o' Finds any values that starts with "a" and ends with "o"
Example
SELECT * FROM Customers
WHERE City LIKE 'ber%';
Try it Yourself »
The following SQL statement selects all customers with a City containing the pattern "es":
Example
SELECT * FROM Customers
WHERE City LIKE '%es%';
Try it Yourself »
Example
SELECT * FROM Customers
WHERE City LIKE '_erlin';
Try it Yourself »
The following SQL statement selects all customers with a City starting with "L", followed by any character,
followed by "n", followed by any character, followed by "on":
Example
SELECT * FROM Customers
WHERE City LIKE 'L_n_on';
Try it Yourself »
Using the [charlist] Wildcard
The following SQL statement selects all customers with a City starting with "b", "s", or "p":
Example
SELECT * FROM Customers
WHERE City LIKE '[bsp]%';
Try it Yourself »
The following SQL statement selects all customers with a City starting with "a", "b", or "c":
Example
SELECT * FROM Customers
WHERE City LIKE '[a-c]%';
Try it Yourself »
Example
SELECT * FROM Customers
WHERE City LIKE '[!bsp]%';
Try it Yourself »
Or:
Example
SELECT * FROM Customers
WHERE City NOT LIKE '[bsp]%';
Try it Yourself »
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
SQL Aliases
SQL Aliases
SQL aliases are used to give a table, or a column in a table, a temporary name.
Each SELECT statement within UNION must have the same number of columns
The columns must also have similar data types
The columns in each SELECT statement must also be in the same order (of data types)
UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL:
Note: The column names in the result-set are usually equal to the column names in the first SELECT statement
in the UNION.
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
The following SQL statement lists the number of customers in each country, sorted high to low:
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
The EXISTS operator returns true if the subquery returns one or more records.
EXISTS Syntax
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
EG
IFNOTEXISTS(SELECT*FROM EmployeeMaster)
BEGIN
Print'done'
END
IFEXISTS(SELECT*FROM EmployeeMaster)
BEGIN
Print'done'
END
The SQL ANY and ALL Operators
The ANY and ALL operators are used with a WHERE or HAVING clause.
The ANY operator returns true if any of the subquery values meet the condition.
The ALL operator returns true if all of the subquery values meet the condition.
ANY Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name FROM table_name WHERE condition);
ALL Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name FROM table_name WHERE condition);
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity > 99);
Example
SELECT ProductName
FROM Products
WHERE ProductID = ALL (SELECT ProductID FROM OrderDetails WHERE Quantity = 10);
SELECT *
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;
The new table will be created with the column-names and types as defined in the old table. You can create new
column names using the AS clause.
The following SQL statement uses the IN clause to copy the table into a new table in another database:
The following SQL statement copies only a few columns into a new table:
The following SQL statement copies only the German customers into a new table:
The following SQL statement copies data from more than one table into a new table:
Tip: SELECT INTO can also be used to create a new, empty table using the schema of another. Just add a
WHERE clause that causes the query to return no data:
INSERT INTO SELECT requires that data types in source and target tables match
The existing records in the target table are unaffected
Copy only some columns from one table into another table:
Example
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers;
The following SQL statement copies "Suppliers" into "Customers" (fill all columns):
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
SELECT SupplierName, ContactName, Address, City, PostalCode, Country FROM Suppliers;
The following SQL statement copies only the German suppliers into "Customers":
Example
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers
WHERE Country='Germany';
SQL Dates
The most difficult part when working with dates is to be sure that the format of the date you are trying to insert,
matches the format of the date column in the database.
As long as your data contains only the date portion, your queries will work as expected. However, if a time
portion is involved, it gets more complicated.
Note: The date types are chosen for a column when you create a new table in your database!
SQL Injection
SQL injection is a code injection technique that might destroy your database.
SQL injection is the placement of malicious code in SQL statements, via web page input.
Look at the following example which creates a SELECT statement by adding a variable (txtUserId) to a select
string. The variable is fetched from user input (getRequestString):
Example
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
The rest of this chapter describes the potential dangers of using user input in SQL statements.
105 OR 1=1
UserId:
The SQL above is valid and will return ALL rows from the "Users" table, since OR 1=1 is always TRUE.
Does the example above look dangerous? What if the "Users" table contains names and passwords?
SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1;
A hacker might get access to all the user names and passwords in a database, by simply inserting 105 OR 1=1
into the input field.
Username:
John Doe
Password:
myPass
Example
uName = getRequestString("username");
uPass = getRequestString("userpassword");
sql = 'SELECT * FROM Users WHERE Name ="' + uName + '" AND Pass ="' + uPass + '"'
Result
SELECT * FROM Users WHERE Name ="John Doe" AND Pass ="myPass"
A hacker might get access to user names and passwords in a database by simply inserting " OR ""=" into the
user name or password text box:
User Name:
Password:
The code at the server will create a valid SQL statement like this:
Result
SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""
The SQL above is valid and will return all rows from the "Users" table, since OR ""="" is always TRUE.
A batch of SQL statements is a group of two or more SQL statements, separated by semicolons.
The SQL statement below will return all rows from the "Users" table, then delete the "Suppliers" table.
Example
SELECT * FROM Users; DROP TABLE Suppliers
Example
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
Result
SELECT * FROM Users WHERE UserId = 105; DROP TABLE Suppliers;
SQL parameters are values that are added to an SQL query at execution time, in a controlled manner.
The SQL engine checks each parameter to ensure that it is correct for its column and are treated literally, and
not as part of the SQL to be executed.
Another Example
txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City) Values(@0,@1,@2)";
db.Execute(txtSQL,txtNam,txtAdd,txtCit);
Examples
The following examples shows how to build parameterized queries in some common web languages.
txtUserId = getRequestString("UserId");
sql = "SELECT * FROM Customers WHERE CustomerId = @0";
command = new SqlCommand(sql);
command.Parameters.AddWithValue("@0",txtUserID);
command.ExecuteReader();
txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City) Values(@0,@1,@2)";
command = new SqlCommand(txtSQL);
command.Parameters.AddWithValue("@0",txtNam);
command.Parameters.AddWithValue("@1",txtAdd);
command.Parameters.AddWithValue("@2",txtCit);
command.ExecuteNonQuery();
This reference contains the string, numeric, date, conversion, and advanced functions in SQL Server.
Function Description
ASCII Returns the number code that represents the specific character
STUFF Deletes a sequence of characters from a string and then inserts another sequence of
characters into the string, starting at a specified position
Function Description
CEILING Returns the smallest integer value that is greater than or equal to a number
FLOOR Returns the largest integer value that is equal to or less than a number
Function Description
DATEDIFF Returns the difference between two date values, based on the interval specified
DAY Returns the day of the month (from 1 to 31) for a given date
YEAR Returns the year (as a four-digit number) for a given date
Function Description
Function Description
SESSION_USER Returns the user name of the current session in the SQL Server database
SYSTEM_USER Returns the login name information for the current user in the SQL Server database
SQL ISNULL(),
We have the following SELECT statement:
SELECT ProductName,UnitPrice*(UnitsInStock+UnitsOnOrder)
FROM Products
In the example above, if any of the "UnitsOnOrder" values are NULL, the result is NULL.
Microsoft's ISNULL() function is used to specify how we want to treat NULL values.
Below, if "UnitsOnOrder" is NULL it will not harm the calculation, because ISNULL() returns a zero if the value is
NULL:
SQL Server
SQL Operators
+ Add Try it
- Subtract Try it
* Multiply Try it
/ Divide Try it
% Modulo Try it
Operator Description
| Bitwise OR
^ Bitwise exclusive OR
SQL Comparison Operators
= Equal to Try it
Operator Description
+= Add equals
-= Subtract equals
*= Multiply equals
/= Divide equals
%= Modulo equals
ALL TRUE if all of the subquery values meet the condition Try it
ANY TRUE if any of the subquery values meet the condition Try it
varchar(n) Variable width character string 8,000 characters 2 bytes + number of chars
varchar(max) Variable width character string 1,073,741,824 characters 2 bytes + number of chars
Text Variable width character string 2GB of text data 4 bytes + number of chars
5-17 bytes
decimal(p,s) Fixed precision and scale numbers.
float(n) Floating precision number data from -1.79E + 308 to 1.79E + 308. 4 or 8 bytes
Datetime From January 1, 1753 to December 31, 9999 with an accuracy of 3.33 8 bytes
milliseconds
datetime2 From January 1, 0001 to December 31, 9999 with an accuracy of 100 6-8 bytes
nanoseconds
Smalldatetime From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute 4 bytes
Date Store a date only. From January 1, 0001 to December 31, 9999 3 bytes
Datetimeoffset The same as datetime2 with the addition of a time zone offset 8-10 bytes
Timestamp Stores a unique number that gets updated every time a row gets created
or modified. The timestamp value is based upon an internal clock and
does not correspond to real time. Each table may have only one
timestamp variable
or
SELECT column_name
FROM table_name AStable_alias
BETWEEN SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
CREATE DATABASE CREATE DATABASE database_name
CREATE TABLE CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
...
)
CREATE INDEX CREATE INDEX index_name
ON table_name (column_name)
or
or
or
or
SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_table_name
SELECT TOP SELECT TOP number|percentcolumn_name(s)
FROM table_name
TRUNCATE TABLE TRUNCATE TABLE table_name
UNION SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
UNION ALL SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
UPDATE UPDATE table_name
SET column1=value, column2=value,...
WHERE some_column=some_value
WHERE SELECT column_name(s)
FROM table_name
WHERE column_name operator value
Different Types of SQL Server 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 of Function
1. 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
Scalar functions operate on a single value and returns a single value. Below is the list of some useful Sql Server Scalar
functions.
Scalar Function
Description
abs(-10.67)
rand(10)
round(17.56719,3)
This will round off the given number to 3 places of decimal means 17.567
upper('dotnet')
lower('DOTNET')
ltrim(' dotnet')
This will remove the spaces from left hand side of 'dotnet' string.
convert(int, 15.56)
This will convert the given float value to integer means 15.
2. Aggregate Function
Aggregate functions operate on a collection of values and returns a single value. Below is the list of some useful Sql
Server Aggregate functions.
Aggregate Function
Description
max()
min()
avg()
count()
1. 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.
1.
1. --Create a table
2. CREATETABLE Employee
3. (
4. EmpID int PRIMARYKEY,
5. FirstName varchar(50)NULL,
6. LastNamevarchar(50)NULL,
7. Salary int NULL,
8. Address varchar(100)NULL,
9. )
10. --Insert Data
11. InsertintoEmployee(EmpID,FirstName,LastName,Salary,Address)Values(1,'Mohan','Chauah
n',22000,'Delhi');
12. InsertintoEmployee(EmpID,FirstName,LastName,Salary,Address)Values(2,'Asif','Khan',1
5000,'Delhi');
13. InsertintoEmployee(EmpID,FirstName,LastName,Salary,Address)Values(3,'Bhuvnesh','Sha
kya',19000,'Noida');
14. InsertintoEmployee(EmpID,FirstName,LastName,Salary,Address)Values(4,'Deepak','Kumar
',19000,'Noida');
15. --See created table
16. Select*from Employee
2.
1. --Create function to get emp full name
2. CreatefunctionfnGetEmpFullName
3. (
4. @FirstName varchar(50),
5. @LastName varchar(50)
6. )
7. returns varchar(101)
8. As
9. Beginreturn(Select@FirstName +' '+@LastName);
10. end
3.
1. --Calling the above created function
2. Selectdbo.fnGetEmpFullName(FirstName,LastName)as Name, Salary from Employee
2.
1. --Now call the above created function
2. Select*fromfnGetMulEmployee()
3.
1. --Now see the original table. This is not affected by above function update command
2. Select*from Employee
Note
1. Unlike Stored Procedure, Function returns only single value.
2. Unlike Stored Procedure, Function accepts only input parameters.
3. Unlike Stored Procedure, Function is not used to Insert, Update, Delete data in database table(s).
4. Like Stored Procedure, Function can be nested up to 32 level.
5. User Defined Function can have upto 1023 input parameters while a Stored Procedure can have upto 2100 input
parameters.
6. User Defined Function can't returns XML Data Type.
7. User Defined Function doesn't support Exception handling.
8. User Defined Function can call only Extended Stored Procedure.
9. User Defined Function doesn't support set options like set ROWCOUNT etc.
Sql Server - Stored Procedure
Stored Procedure: Stored Procedure in SQL Server can be defined as the set of logical groups 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.
CreateProcedure Procedure-name
(
Input parameters,
Output Parameters (If required)
)
As
Begin
Sql statement used in the stored procedure
End
Now, suppose we need to create a Stored Procedure which will return a student name whose studentid is
given as the input parameter to the stored procedure. Then, the Stored Procedure will be:
CreatePROCEDUREGetstudentname(
@studentidINT--Input parameter ,Studentid of the student
)
AS
BEGIN
SELECTFirstname+' '+LastnameFROMtbl_StudentsWHEREstudentid=@studentid
END
We can also collect the student name in the output parameter of the Stored Procedure. For example:
/*
GetstudentnameInOutputVariable is the name of the stored procedure which
uses output variable @Studentname to collect the student name returns by the
stored procedure
*/
CreatePROCEDUREGetstudentnameInOutputVariable
(
/*
Stored Procedure GetstudentnameInOutputVariable is modified to collect the
email address of the student with the help of the Alert Keyword
*/
AlterPROCEDUREGetstudentnameInOutputVariable
(
/*
This Stored procedure is used to Insert value into the table tbl_students.
*/
CreateProcedureInsertStudentrecord
(
@StudentFirstNameVarchar(200),
@StudentLastNameVarchar(200),
@StudentEmailVarchar(50)
)
As
Begin
Insertintotbl_Students (Firstname, lastname, Email)
Values(@StudentFirstName, @StudentLastName,@StudentEmail)
End
ExecuteGetstudentname1
ExecGetstudentname1
Insert Operation
We can insert records into the table(s) using stored procedure by passing data in input parameters. Below code is used
to insert record in the table "Employee" using stored procedure
1.
1. CREATETABLE Employee
2. (
3. EmpID int primarykey, Name varchar(50),
4. Salary int,
5. Address varchar(100)
6. )
1.
1. InsertintoEmployee(EmpID,Name,Salary,Address)Values(1,'Mohan',16000,'Delhi')
2. InsertintoEmployee(EmpID,Name,Salary,Address)Values(2,'Asif',15000,'Delhi')
3. InsertintoEmployee(EmpID,Name,Salary,Address)Values(3,'Bhuvnesh',19000,'Noida')
4. --See table
5. SELECT*FROM Employee
1.
1. CREATEPROCEDUREusp_InsertEmployee
2. @flag bit output,-- return 0 for fail,1 for success
3. @EmpID int,
4. @Name varchar(50),
5. @Salary int,
6. @Address varchar(100)
7. AS
8. BEGIN
9. BEGINTRANSACTION
10. BEGIN TRY
11. InsertintoEmployee(EmpID,Name,Salary,Address)Values(@EmpID,@Name,@Salary,@Address)
12. set@flag=1;
13. IF@@TRANCOUNT >0
14. BEGINcommitTRANSACTION;
15. END
16. END TRY
17. BEGIN CATCH
18. IF@@TRANCOUNT >0
19. BEGINrollbackTRANSACTION;
20. END
21. set@flag=0;
22. END CATCH
23. END
1.
1. --Execute above created procedure to insert rows into table
2. Declare@flag bit
3. EXECusp_InsertEmployee@flag output,1,'Deepak',14000,'Noida'
4. if@flag=1
5. print'Successfully inserted'
6. else
7. print'There is some error'
1.
1. --Execute above created procedure to insert rows into table
2. Declare@flag bit
3. EXECusp_InsertEmployee@flag output,4,'Deepak',14000,'Noida'
4. if@flag=1
5. print'Successfully inserted'
6. else
7. print'There is some error'
1.
1. --now see modified table
2. Select*from Employee
Retrieve Operation
We can retrieve data from one or more tables/views with the help of join, using stored procedure. We can put multiple
sql statements with in a single stored procedure. Below code is used to fetch data from a table "Employee" using
stored procedure
1.
1. -- first we Insert data in the table
2. InsertintoEmployee(EmpID,Name,Salary,Address)Values(1,'Mohan',16000,'Delhi')
3. InsertintoEmployee(EmpID,Name,Salary,Address)Values(2,'Asif',15000,'Delhi')
4. InsertintoEmployee(EmpID,Name,Salary,Address)Values(3,'Bhuvnesh',19000,'Noida')
5. go
6. --Now we create a procedure to fetch data
7. CREATEPROCEDUREusp_SelectEmployee
8. As
9. Select*from Employee ORDERByEmpID
1.
1. --Execute above created procedure to fetch data
2. execusp_SelectEmployee
Update Operation
We can update records of the table(s) using stored procedure by passing data in input parameters. Below code is used
to update a table "Employee" using stored procedure
1.
1. CREATEPROCEDUREusp_UpdateEmployee
2. @flag bit output,-- return 0 for fail,1 for success
3. @EmpID int,
4. @Salary int,
5. @Address varchar(100)
6. AS
7. BEGIN
8. BEGINTRANSACTION
9. BEGIN TRY
10. Update Employee set Salary=@Salary, Address=@Address
11. WhereEmpID=@EmpID
12. set@flag=1;
13. IF@@TRANCOUNT >0
14. BEGINcommitTRANSACTION;
15. END
16. END TRY
17. BEGIN CATCH
18. IF@@TRANCOUNT >0
19. BEGINrollbackTRANSACTION;
20. END
21. set@flag=0;
22. END CATCH
23. END
1.
1. --Execute above created procedure to update table
2. Declare@flag bit
3. EXECusp_UpdateEmployee@flag output,1,22000,'Noida'
4. if@flag=1print'Successfully updated'
5. else
6. print'There is some error'
1.
1. --now see updated table
2. Select*from Employee
Delete Operation
We can delete records of the table(s) using stored procedure by passing data in input parameters. Below code is used
to update a table "Employee" using stored procedure
1.
1. CREATEPROCEDUREusp_DeleteEmployee
2. @flag bit output,-- return 0 for fail,1 for success
3. @EmpID int
4. AS
5. BEGIN
6. BEGINTRANSACTION
7. BEGIN TRY
8. Deletefrom Employee WhereEmpID=@EmpID set@flag=1;
9. IF@@TRANCOUNT >0
10. BEGINcommitTRANSACTION;
11. END
12. END TRY
13. BEGIN CATCH
14. IF@@TRANCOUNT >0
15. BEGINrollbackTRANSACTION;
16. END
17. set@flag=0;
18. END CATCH
19. END
1.
1. --Execute above created procedure to delete rows from table
2. Declare@flag bit
3. EXECusp_DeleteEmployee@flag output,4
4. if@flag=1
5. print'Successfully deleted'
6. else
7. print'There is some error'
1.
1. --now see modified table
2. Select*from Employee
Note
1. In stored procedure we use output parameter to return multiple values.
2. Generally we use output parameter in stored procedure to get status of the operation as I used above "@flag" output
parameter to get operations status whether these are successfully executed or not.
Temporary Table in SQL Server
Introduction
A temporary table is one of the best features of SQL Server. If you want to perform a large amount of operations in SQL or work on a
large query of SQL then you need to store some data or maybe a table of data for the operation. To store a large amount of data we
can create a temporary table and store the table with for some period of time.
You can perform any type of operation like insert, update, delete, selection, join and so on. One of the best features of a temporary
table is you can store temporary data inside it and the temporary table will be automatically deleted when the current client session is
terminated.
1. Local Temporary Table: These are only available for the current instance; it will be automatically deleted when the user is
disconnected from the instance. To create a local temporary table, we use the table name with a # (hash) prefix.
2. Global Temporary Table: This table is the same as a permanent table but the difference is only that when all the
connections are closed or all the instances are deleted then the table will be deleted. To create a globaltemporary table, we
use a table name with a ## (double hash) prefix.
As we know, there are two types of temporary tables, global and local.
To create a local temporary table as I described we will use "# symbol" so the syntax of the local temporary table is:
For Example
For Example
After closing it refresh the object browser and your table will be deleted.
Global Temporary Table
To create a global temporary table as I said we use "## symbol" so the syntax of the local temporary table is:
For Example
Note: This table is a global temporary table so it will be deleted when all the instances or the session that was created are closed.
Key Points
1. Temporary Tables exist at Databases > System Databases >tempdb> Temporary Tables
2. Temporary tables are automatically deleted; there is no need to delete them explicitly when you are working.
Understanding Case Expression in SQL Server with
Example
Sometimes, you required to fetch or modify the records based on some conditions. In this case, you may
use cursor or loop for modify your records. In this situation Case expression is best alternative for
Cursor/looping and also provides better performance.
You can use CASE expressions anywhere in the SQL Query like CASE expressions can be used with in
SELECT statement, WHERE clauses, Order by clause, HAVING clauses, Insert, UPDATE and DLETE
statements.
Syntax
1. CASE expression
2. WHEN expression1 THEN Result1
3. WHEN expression2 THEN Result2
4. ELSE ResultN
5. END
Syntax
1. CASE
2. WHEN Boolean_expression1 THEN Result1
3. WHEN Boolean_expression2 THEN Result2
4. ELSE ResultN
5. END
Firstly, we will create a table and insert some data into the table.
Output
We use above Employee table for PIVOT and UNPIVOT relational operator examples. First we read about PIVOT realational operator.
PIVOT
PIVOT relational operator convert data from row level to column level. PIVOT rotates a table-valued expression by turning the unique
values from one column in the expression into multiple columns in the output. Using PIVOT operator we can perform aggregate
operation where we required.
Syntax
Example 1
Output:
In above query we calculate the sum of sales for Pankaj, Rahul and Sandeep employee corresponding to year value.
Example 2
Output:
When we execute above query, SQL Server throws an error because we can’t provide integer value as a column name directly. To
remove this error use the brackets before each integer value as in the following code snippet:
Output
Example 3
In previous examples we wrote the name of pivot column. This approach is useful if we know all possible values for pivot column. But it
is not fix that column always remain same, pivot column may be increased or decreased in future.
Let us take previous example. In previous example we wrote 2010,2011 and 2012 as pivot column. But it is not fix that these column will
not change in future , so what should we do if there is a possibility that column number may change in future.
In such a condition we should use dynamic query. Firstly, retrieve all unique values from pivot column and after that write a dynamic
query to execute it with pivot query at run time.
1. /*Declare Variable*/
2. DECLARE @Pivot_Column [nvarchar](max);
3. DECLARE @Query [nvarchar](max);
4.
5. /*Select Pivot Column*/
6. SELECT @Pivot_Column= COALESCE(@Pivot_Column+',','')+ QUOTENAME(Year) FROM
7. (SELECT DISTINCT [Year] FROM Employee)Tab
8.
9. /*Create Dynamic Query*/
10. SELECT @Query='SELECT Name, '+@Pivot_Column+'FROM
11. (SELECT Name, [Year] , Sales FROM Employee )Tab1
12. PIVOT
13. (
14. SUM(Sales) FOR [Year] IN ('+@Pivot_Column+')) AS Tab2
15. ORDER BY Tab2.Name'
16.
17. /*Execute Query*/
18. EXEC sp_executesql @Query
Output
UNPIVOT
UNPIVOT relational operator is reverse process of PIVOT relational operator. UNPIVOT relational operator convert data from column
level to row level.
Example 4:
Suppose that output of example 2 is stored in Temp Variable. Now we want to rotate column identifiers Pankaj, Sandeep, Rahul into
row values. For this we use the UNPIVOT relational operator.
Output
We can perform first PIVOT operation and after that UNPIVOT operation on same table in single query as in the following code snippet.
Output
Note
UNPIVOT operation is a reverse process of PIVOT operation, but UNPIVOT is not the exact reverse of PIVOT. If PIVOT performs an
aggregation and merges multiple rows into a single row in the output, then UNPIVOT can’t reproduce the original table-valued
expression result because rows have been merged. So conclusion is that if PIVOT operation merges multiple row in a single row, then
UNPIVOT operation can’t retrieve original table from the output of PIVOT operation. But if PIVOT operation doesn’t merge multiple row
in a single row, then UNPIVOT operation can retrieve original table from the output of PIVOT operation.
Output
We can see that both the tables are not same. First table contain 10 rows but the above table contains only 7 rows. This difference
occur due to the PIVOT operation. PIVOT operation merge the (4,7,8) row in a single row and merge the (3,5) row in a single row. So
UNPIVOT operation can’t retrieve original table.
Now we perform PIVOT and UNPIVOT operation for this table and compare the resultant table from this table.
Output
CTE
CTE stands for Common Table expressions. It was introduced with SQL
Server 2005. It is a temporary result set and typically it may be a result of
complex sub-query. Unlike temporary table its life is limited to the current
query. It is defined by using WITH statement. CTE improves readability
and ease in maintenance of complex queries and sub-queries. Always
begin CTE with semicolon.
Temporary Tables
In SQL Server, temporary tables are created at run-time and you can do
all the operations which you can do on a normal table. These tables are
created inside Tempdb database. Based on the scope and behavior
temporary tables are of two types as given below-
Local temp tables are only available to the SQL Server session or
connection (means single user) that created the tables. These are
automatically deleted when the session that created the tables has
been closed. Local temporary table name is stared with single hash
("#") sign.
1. CREATE TABLE #LocalTemp
2. (
3. UserIDint,
4. Namevarchar(50),
5. Addressvarchar(150)
6. )
7. GO
8. insert into#LocalTemp values ( 1, 'Shailendra','Noida');
9. GO
10. Select*from#LocalTemp
The scope of Local temp table exist to the current session of current
user means to the current query window. If you will close the current
query window or open a new query window and will try to find above
created temp table, it will give you the error.
Global temporary tables are visible to all SQL Server connections while
Local temporary tables are visible to only current SQL Server
connection.
Table Variable
This acts like a variable and exists for a particular batch of query
execution. It gets dropped once it comes out of batch. This is also created
in the Tempdb database but not the memory. This also allows you to
create primary key, identity at the time of Table variable declaration but
not non-clustered index.
1. GO
2. DECLARE @TProduct TABLE
3. (
4. SNo INT IDENTITY(1,1),
5. ProductID INT,
6. Qty INT
7. )
8. --Insert data to Table variable @Product
9. INSERT INTO @TProduct(ProductID,Qty)
10. SELECT DISTINCT ProductID,Qty FROM ProductsSales ORDER BY ProductID
ASC
11. --Select data
12. Select*from@TProduct
13.
14. --Next batch
15. GO
16. Select*from@TProduct--gives error innext batch
17.
Note
1. Temp Tables are physically created in the Tempdb database. These tables act as the
normal table and also can have constraints, index like normal tables.
2. CTE is a named temporary result set which is used to manipulate the complex sub-
queries data. This exists for the scope of statement. This is created in memory
rather than Tempdb database. You cannot create any index on CTE.
3. Table Variable acts like a variable and exists for a particular batch of query
execution. It gets dropped once it comes out of batch. This is also created in the
Tempdb database but not the memory.
How to insert values to identity column in SQL
Server
Identity field is usually used as a primary key. When you insert a new record into your table, this field
automatically assign an incremented value from the previous entry. Usually, you can't insert your own
value to this field.
In this article, I am going to expose the tips for inserting your own value to this field. It is simple and
easy. Consider you have the following Customer table.
1. CREATE TABLE Customer
2. (
3. ID int IDENTITY,
4. Namevarchar(100),
5. Addressvarchar(200)
6. )
Now, I am trying to insert a record into Customer table with identity field like as then I will get the error
message as shown below.
1. INSERT INTO Customer(ID,Name,Address) VALUES(1,'Shakham','Delhi')
Note
1. Usually, we use this trick when we have deleted some rows from the table and we want the data in a sequence.
2. After Inserting your own value to identity field don't forget to set IDENTITY_INSERT OFF
Reseed the Identity field
You can also reseed the identity field value. By doing so identity field values will start with a new defined
value.
Suppose you want to reseed the Customer table ID field from 3 then the new record s will be inserted
with ID 4,5,6..and so on.
1. --Reseeding the identity
2. DBCC checkident(Customer, RESEED,3)
3.
4. INSERT INTO Customer(Name,Address) VALUES('Geeta','Noida')
Calculate Running Total, Total of a Column and Row
Many times, you required to show information of each transaction and also keep a Running Total and
Final Total like GridView in Asp.Net. In this article, I am going to explain, how can you achieve this using
SQL Query in simple and easy way.
Suppose you have the below CustomerOrders table and has the data as shown below:
1. CREATE TABLE CustomerOrders
2. (
3. OrderIDint identity,
4. AmountDecimal(8,2),
5. OrderDateSmallDatetimedefaultgetdate()
6. )
7.
8. Go
9.
10. INSERT INTO CustomerOrders(Amount)Values(120.12)
11. INSERT INTO CustomerOrders(Amount)Values(20.12)
12. INSERT INTO CustomerOrders(Amount)Values(10.12)
13. INSERT INTO CustomerOrders(Amount)Values(30.12)
14. INSERT INTO CustomerOrders(Amount)Values(40)
15.
16. GO
17.
18. SELECT * FROM CustomerOrders
1. Super Key
Super key is a set of one or more than one keys that can be used to identify a record uniquely in a
table.Example : Primary key, Unique key, Alternate key are subset of Super Keys.
2. Candidate Key
A Candidate Key is a set of one or more fields/columns that can identify a record uniquely in a table.
There can be multiple Candidate Keys in one table. Each Candidate Key can work as Primary Key.
Example: In below diagram ID, RollNo and EnrollNo are Candidate Keys since all these three fields
can be work as Primary Key.
3. Primary Key
Primary key is a set of one or more fields/columns of a table that uniquely identify a record in
database table. It can not accept null, duplicate values. Only one Candidate Key can be Primary Key.
4. Alternate key
A Alternate key is a key that can be work as a primary key. Basically, it is a candidate key that
currently is not primary key.
Example: In below diagram RollNo and EnrollNo becomes Alternate Keys when we define ID as
Primary Key.
5. Composite/Compound Key
Composite Key is a combination of more than one fields/columns of a table. It can be a Candidate
key, Primary key.
6. Unique Key
Uniquekey is a set of one or more fields/columns of a table that uniquely identify a record in
database table. It is like Primary key but it can accept only one null value and it cannot have
duplicate values. For more help refer the article Difference between primary key and unique key.
7. Foreign Key
Foreign Key is a field in database table that is Primary key in another table. It can accept multiple
null, duplicate values. For more help refer the article Difference between primary key and foreign
key.
Example : We can have a DeptID column in the Employee table which is pointing to DeptID column
in a department table where it a primary key.
Note
1. Practically in database, we have only three types of keys Primary Key, Unique Key and Foreign Key. Other types of
keys are only concepts of RDBMS which you should know.
Different Types of SQL Server Views
Views are virtual tables that are compiled at run time. The data associated with views are not physically
stored in the view, but it is stored in the base tables of the view. A view can be made over one or more
database tables. Generally we put those columns in view that we need to retrieve/query again and again.
Once you have created the view, you can query view like as table. We can make index, trigger on view.
In Sql Server we make views for security purpose since it restricts the user to view some columns/fields
of the table(s). Views show only those columns that are present in the query which is used to make
view.One more advantage of Views is, data abstraction since the end user is not aware of all the data
present in database table.
Syntax for View
1. CREATE VIEW view_name
2. AS
3. select_statement[]
Types of Views
In Sql Server we have two types of views.
2. Catalog View
Catalog Views were introduced with SQL Server 2005. These are used to show database self
describing information.
1. select*fromsys.tables
1. Simple View
When we create a view on a single table, it is called simple view.
1. --NowInsert data to table Employee_Test
2. InsertintoEmployee_Test values ('Amit','PHP',12000,'SE');
3. InsertintoEmployee_Test values ('Mohan','ASP.NET',15000,'TL');
4. InsertintoEmployee_Test values ('Avin','C#',14000,'SE');
5. InsertintoEmployee_Test values ('Manoj','JAVA',22000,'SSE');
6. InsertintoEmployee_Test values ('Riyaz','VB',18000,'TH');
7. --Now create view on single table Employee_Test
8. create VIEW vw_Employee_Test
9. AS
10. SelectEmp_ID,Emp_Name,Emp_Designation
11. FromEmployee_Test
In simple view we can insert, update, delete data. We can only insert data in simple view if
we have primary key and all not null fields in the view.
14. --Insert data to view vw_Employee_Test
15. insert intovw_Employee_Test(Emp_Name,Emp_Designation) values ('Shailu','SSE')
16. --Now see the affected view
17. Select*fromvw_Employee_Test
2. Complex View
When we create a view on more than one table, it is called complex view.
1. --Create another table
2. create table Personal_Info
3. (
4. Emp_Namevarchar(55),
5. FNamevarchar(55),
6. DOB varchar(55),
7. Addressvarchar(55),
8. Mobileint,
9. Statevarchar(55)
10. )
11. --NowInsert data
12. InsertintoPersonal_Info values ('G.Chaudary','22-10-
1985','Ghaziabad',96548922,'UP');
13. InsertintoPersonal_Info values ('B.S.Chauhan','02-07-
1986','Haridwar',96548200,'UK');
14. InsertintoPersonal_Info values ('A.Panwar','30-04-1987','Noida',97437821,'UP');
15. InsertintoPersonal_Info values ('H.C.Patak','20-07-
1986','Rampur',80109747,'UP');
16. InsertintoPersonal_Info values ('M.Shekh','21-10-
1985','Delhi',96547954,'Delhi');
17. --Now create view on two tables Employee_TestandPersonal_Info
18. Create VIEW vw_Employee_Personal_Info
19. As
20. Selecte.Emp_ID,e.Emp_Name,e.Emp_Designation,p.DOB,p.Mobile
21. FromEmployee_Test e INNER JOIN Personal_Info p
22. One.Emp_Name= p.Emp_Name
Note
1. We make views for security purpose since it restricts the user to view some columns/fields of the table(s).
2. One more advantage of Views is, data abstraction since the end user is not aware of all the data present in database
table
SQL Server Exceptions Working
SQL Server has an exception model to handle exceptions and errors that occurs in T-SQL statements.
Exception handling in Sql Server is like as exception handling in other programming language. To
understand exception handling, first we need to know how many types of exception we have in Sql
Server.
Types of Exceptions
1. Statement-Level Exception
This type of exception aborts only the current running statement within a batch of T-SQL statements.
The rest of the T-SQL statements will execute successfully if they have no exceptions. Let us see the
below example.
1. --Batch
2. SELECT POWER(4,28)
3. PRINT 'This statement will execute'
4. GO
2. Batch-Level Exception
This type of exception aborts only the batch in which exception occurs. The rest of the batches will
execute successfully if they have no exceptions. The statement in which exception occurs will be
aborted and the remaining T-SQL statements within the batch will also stopped.
1. --FirstBatch
2. DECLARE @var DECIMAL;
3. set@var=CONVERT(DECIMAL,'xyz')
4. PRINT @var
5. PRINT 'This statement will not execute'
6. GO
7. --SecondBatch
8. DECLARE @var DECIMAL;
9. set@var=CONVERT(DECIMAL,'12.35')
10. PRINT @var
11. PRINT 'This statement will execute'
12. GO
3. Parsing and Scope-Resolution Exception
This type of exception occurs during the parsing and during the scope-resolution phase of
compilation. This exception appears to behave just like batch-level exceptions. However, this has a
little different behavior.
If the exception occurs in the same scope of the batch, it behaves just like a batch-level exception.If
the exception occurs in a lower level of scope of the batch, it behaves just like statement-level
exception.
Parsing Exception
1. --ParsingError
2. SELECTEmpID,Name FROM Employee
3. PRINT 'This statement will execute'
4. GO
2. ERROR_LINE ()
This returns the line number of T-SQL statement that caused error.
3. ERROR_SEVERITY()
This returns the severity level of the error.
4. ERROR_STATE ()
This returns the state number of the error.
5. ERROR_PROCEDURE ()
This returns the name of the stored procedure or trigger where the error occurred.
6. ERROR_MESSAGE ()
This returns the full text of error message. The text includes the values supplied for any substitutable
parameters, such as lengths, object names, or times.
Exception handling example
1. BEGIN TRY
2. DECLARE @num INT,@msgvarchar(200)
3. ----Divideby zero to generate Error
4. SET @num=5/0
5. PRINT 'This will not execute'
6. END TRY
7. BEGIN CATCH
8. PRINT 'Error occured that is'
9. set@msg=(SELECT ERROR_MESSAGE())
10. print@msg;
11. END CATCH
12. GO
1. BEGIN TRY
2. DECLARE @num INT
3. ----Divideby zero to generate Error
4. SET @num=5/0
5. PRINT 'This will not execute'
6. END TRY
7. BEGIN CATCH
8. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage;
9. END CATCH;
10. GO
Note
1. A TRY..CATCH block combination catches all the errors that have a severity between 11 and 19.
2. The CATCH block is executed only if there is an error occurs in T-SQL statements within TRY block otherwise the
CATCH block is ignored.
3. Each TRY block is associated with only one CATCH block and vice versa
4. TRY and CATCH blocks can’t be separated with the GO statement. We need to put both TRY and CATCH blocks within
the same batch.
5. TRY..CATCH blocks can be used with transactions. We check the number of open transactions by using
@@TRANCOUNT function in Sql Server.
6. XACT_STATE function within the TRY..CATCH block can be used to check whether a open transaction is committed or
not. It will return -1 if transaction is not committed else returns 1.
SQL Server Transactions Management
A transaction is a set of T-SQL statements that are executed together as a unit like as a single T-SQL
statement. If all of these T-SQL statements executed successfully, then a transaction is committed and
the changes made by T-SQL statements permanently saved to database. If any of these T-SQL
statements within a transaction fail, then the complete transaction is cancelled/ rolled back.
We use transaction in that case, when we try to modify more than one tables/views that are related to
one another. Transactions affect SQL Server performance greatly. Since When a transaction is initiated
then it locks all the tables data that are used in the transaction. Hence during transaction life cycle no
one can modify these tables’ data that are used by the transaction. The reason behind the locking of the
data is to maintain Data Integrity.
Types of Transactions
1. Implicit Transaction
Implicit transactions are maintained by SQL Server for each and every DDL (CREATE, ALTER, DROP,
TRUNCATE), DML (INSERT, UPDATE, DELETE) statements. All these T-SQL statements runs under the
implicit transaction. If there is an error occurs within these statements individually, SQL Server will
roll back the complete statement.
2. Explicit Transaction
Explicit transactions are defined by programmers. In Explicit transaction we include the DML
statements that need to be executed as a unit.
Transactions Example
1. CREATE TABLE Department
2. (
3. DeptIDint PRIMARY KEY,
4. DeptNamevarchar(50) NULL,
5. Locationvarchar(100) NULL,
6. )
7. GO
8. CREATE TABLE Employee
9. (
10. EmpIDint PRIMARY KEY,
11. Namevarchar(50) NULL,
12. Salaryint NULL,
13. Addressvarchar(100) NULL,
14. DeptIDint foreign Key references Department(DeptID)
15. )
1. --NowInsert data
2. INSERT INTO Department(DeptID,DeptName,Location)VALUES(1,'IT','Delhi')
3. GO
4. INSERT INTO Employee(EmpID,Name,Salary,Address,DeptID)VALUES(1,'Mohan',15000,'Delhi',1)
5. SELECT * FROM Department
6. SELECT * FROM Employee
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
3. CLR Triggers
CLR triggers are special type of triggers that based on the CLR (Common Language Runtime) in .net
framework. CLR integration of triggers has been introduced with SQL Server 2008 and allows for
triggers to be coded in one of .NET languages like C#, Visual Basic and F#.
We coded the objects(like trigger) in the CLR that have heavy computations or need references to
objects outside the SQL Server. We can write code for both DDL and DML triggers, using a supported
CLR language like C#, Visual basic and F#. I will discuss CLR trigger later.
4. Logon Triggers
Logon triggers are special type of trigger that fire when LOGON event of Sql Server is raised. This
event is raised when a user session is being established with Sql Server that is made after the
authentication phase finishes, but before the user session is actually established. Hence, all
messages that we define in the trigger such as error messages, will be redirected to the SQL Server
error log. Logon triggers do not fire if authentication fails. We can use these triggers to audit and
control server sessions, such as to track login activity or limit the number of sessions for a specific
login.
Synatx for Logon Trigger
1. CREATE TRIGGER trigger_name
2. ON ALL SERVER
3. [WITH ENCRYPTION]
4. {FOR|AFTER} LOGON
5. AS
6. sql_statement[1...n ]
1. trigger_name
This is the name of the trigger. It should conform to the rules for identifiers in Sql Server.
2. table|view
This is the table/view on which the trigger is to be created.
3. ENCRYPTION
This option is optional. If this option is specified, original text of the CREATE TRIGGER statement will
be encrypted.
4. EXECUTE AS
This option is optional. This option specifies, the security context under which the trigger is executed.
5. FOR/AFTER
FOR/AFTER specifies that the trigger is After Trigger. AFTER is the default, if FOR is the only keyword
specified.AFTER triggers cannot be defined on views.
6. INSTEAD OF
INSTEAD OF specifies that the trigger is Instead Of Trigger.
7. CREATE|ALTER|DROP|INSERT|UPDATE|DELETE
These keywords specify on which action the trigger should be fired. One of these keywords or any
combination of these keywords in any order can be used.
9. AS
After this we specifies the actions and condition that the trigger perform.
10. sql_statement
These are the trigger conditions and actions. The trigger actions specified in the T-SQL statements.
Note
1. The name of a trigger should follow the rules for identifiers.
2. DML trigger can be composed by any T-SQL statements, except CREATE DATABASE, ALTER DATABASE, DROP
DATABASE, LOAD DATABASE, LOAD LOG, RECONFIGURE, RESTORE DATABASE, and RESTORE LOG statements.
3. You cannot create triggers against system tables or dynamic management views. Moreover, the TRUNCATE TABLE
statement does not fire a trigger because this operation does not log individual row deletions.
4. If you use the DATABASE option, the scope of your DDL trigger will be the current database. If you use the ALL SERVER
option, the scope of your DDL triggers to the current server.
5. AFTER triggers cannot be defined on views.
6. AFTER is the default, if FOR is the only keyword specified.
Example
1. --First create table Employee_Demo
2. CREATE TABLE Employee_Demo
3. (
4. Emp_IDint identity,
5. Emp_Namevarchar(55),
6. Emp_Saldecimal(10,2)
7. )
8. --NowInsert records
9. InsertintoEmployee_Demo values ('Amit',1000);
10. InsertintoEmployee_Demo values ('Mohan',1200);
11. InsertintoEmployee_Demo values ('Avin',1100);
12. InsertintoEmployee_Demo values ('Manoj',1300);
13. InsertintoEmployee_Demo values ('Riyaz',1400);
14. --Now create table Employee_Demo_Auditfor logging/backup purpose of table Employee_Demo create table
Employee_Demo_Audit
15. (
16. Emp_IDint,
17. Emp_Namevarchar(55),
18. Emp_Saldecimal(10,2),
19. Audit_Actionvarchar(100),
20. Audit_Timestamp datetime
21. )
Now I am going to explain the use of After Trigger using Insert, Update, Delete statement with example
15. --now select data from both the tables to see trigger action
16. select*fromEmployee_Demo
17. select*fromEmployee_Demo_Audit
18. --Output will be
Trigger have inserted the new record to Employee_Demo_Audit table for insert statement. In this
way we can trace a insert activity on a table using trigger.
19. --now select data from both the tables to see trigger action
20. select*fromEmployee_Demo
21. select*fromEmployee_Demo_Audit
22. --Output will be
Trigger have inserted the new record to Employee_Demo_Audit table for update statement. In this
way we can trace a update activity on a table using trigger.
16. --now select data from both the tables to see trigger action
17. select*fromEmployee_Demo
18. select*fromEmployee_Demo_Audit
19. --Output will be
Trigger have inserted the new record to Employee_Demo_Audit table for delete statement. In this
way we can trace a delete activity on a table using trigger.
Now I am going to explain the use of Instead of Trigger using Insert, Update, Delete statement with
example
Trigger have inserted the new record to Employee_Demo_Audit table for insert statement. In this
way we can apply business validation on the data to be inserted using Instead of trigger and can also
trace a insert activity on a table.
23. --now select data from both the tables to see trigger action
24. select*fromEmployee_Demo
25. select*fromEmployee_Demo_Audit
26. --Output will be
Trigger have inserted the updated record to Employee_Demo_Audit table for update statement. In
this way we can apply business validation on the data to be updated using Instead of trigger and can
also trace a update activity on a table.
23. --now select data from both the tables to see trigger action
24. select*fromEmployee_Demo
25. select*fromEmployee_Demo_Audit
26. --Output will be
Trigger have inserted the deleted record to Employee_Demo_Audit table for delete statement. In this
way we can apply business validation on the data to be deleted using Instead of trigger and can also
trace a delete activity on a table.
2. Open
A Cursor is opened and populated by executing the SQL statement defined by the cursor.
3. Fetch
When cursor is opened, rows can be fetched from the cursor one by one or in a block to do data
manipulation.
4. Close
After data manipulation, we should close the cursor explicitly.
5. Deallocate
Finally, we need to delete the cursor definition and released all the system resources associated with
the cursor.
Syntax to Declare Cursor
Declare Cursor SQL Command is used to define the cursor with many options that impact the scalability
and loading behavior of the cursor. The basic syntax is given below
1. DECLARE cursor_name CURSOR
2. [LOCAL | GLOBAL]--define cursor scope
3. [FORWARD_ONLY | SCROLL]--define cursor movements (forward/backward)
4. [STATIC | KEYSET | DYNAMIC | FAST_FORWARD]--basic type of cursor
5. [READ_ONLY | SCROLL_LOCKS | OPTIMISTIC]--define locks
6. FOR select_statement--define SQL Select statement
7. FOR UPDATE [col1,col2,...coln]--define columns that need to be updated
1. SET NOCOUNT ON
2. DECLARE @Idint
3. DECLARE @namevarchar(50)
4. DECLARE @salaryint
5. DECLARE cur_emp CURSOR
6. STATIC FOR
7. SELECT EmpID,EmpName,SalaryfromEmployee
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
Types of Cursors
1. Static Cursors
A static cursor populates the result set at the time of cursor creation and query result is cached for
the lifetime of the cursor. A static cursor can move forward and backward direction. A static cursor is
slower and use more memory in comparison to other cursor. Hence you should use it only if scrolling
is required and other types of cursors are not suitable.
No UPDATE, INSERT, or DELETE operations are reflected in a static cursor (unless the cursor is closed
and reopened). By default static cursors are scrollable. SQL Server static cursors are always read-
only.
2. Dynamic Cursors
A dynamic cursor allows you to see the data updation, deletion and insertion in the data source while
the cursor is open. Hence a dynamic cursor is sensitive to any changes to the data source and
supports update, delete operations. By default dynamic cursors are scrollable.
3. Forward Only Cursors
A forward only cursor is the fastest cursor among the all cursors but it doesn't support backward
scrolling. You can update, delete data using Forward Only cursor. It is sensitive to any changes to the
original data source.
There are three more types of Forward Only Cursors.Forward_Only KEYSET, FORWARD_ONLY STATIC
and FAST_FORWARD.
A FORWARD_ONLY STATIC Cursor is populated at the time of creation and cached the data to the
cursor lifetime. It is not sensitive to any changes to the data source.
A FAST_FORWARD Cursor is the fastest cursor and it is not sensitive to any changes to the data
source.
1. --DynamicCursorfor DELETE
2. SET NOCOUNT ON
3. DECLARE @Idint
4. DECLARE @namevarchar(50)
5. DECLARE Dynamic_cur_empdelete CURSOR
6. DYNAMIC
7. FOR
8. SELECT EmpID,EmpNamefromEmployee 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*fromEmployee
Forward Only Cursor - Example
1. --ForwardOnlyCursorforUpdate
2. SET NOCOUNT ON
3. DECLARE @Idint
4. DECLARE @namevarchar(50)
5. DECLARE Forward_cur_empupdate CURSOR
6. FORWARD_ONLY
7. FOR
8. SELECT EmpID,EmpNamefromEmployee 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. UpdateEmployee 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*fromEmployee
1. --ForwardOnlyCursorforDelete
2. SET NOCOUNT ON
3. DECLARE @Idint
4. DECLARE @namevarchar(50)
5. DECLARE Forward_cur_empdelete CURSOR
6. FORWARD_ONLY
7. FOR
8. SELECT EmpID,EmpNamefromEmployee 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*fromEmployee
Keyset Driven Cursor - Example
1. --Keyset driven CursorforUpdate
2. SET NOCOUNT ON
3. DECLARE @Idint
4. DECLARE @namevarchar(50)
5. DECLARE Keyset_cur_empupdate CURSOR
6. KEYSET
7. FOR
8. SELECT EmpID,EmpNamefromEmployee 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. UpdateEmployee 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*fromEmployee
1. --KeyseDrivenCursorforDelete
2. SET NOCOUNT ON
3. DECLARE @Idint
4. DECLARE @namevarchar(50)
5. DECLARE Keyset_cur_empdelete CURSOR
6. KEYSET
7. FOR
8. SELECT EmpID,EmpNamefromEmployee 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. GoSelect*fromEmployee
Database Normalization Basics
Normalization or data normalization is a process to organize the data into tabular format (database
tables). A good database design includes the normalization, without normalization a database system
may slow, inefficient and might not produce the expected result. Normalization reduces the data
redundancy and inconsistent data dependency.
Normal Forms
We organize the data into database tables by using normal forms rules or conditions. Normal forms help
us to make a good database design. Generally we organize the data up to third normal form. We rarely
use the fourth and fifth normal form.
To understand normal forms consider the folowing unnormalized database table. Now we will normalize
the data of below table using normal forms.
1. First Normal Form (1NF)
A database table is said to be in 1NF if it contains no repeating fields/columns. The process of
converting the UNF table into 1NF is as follows:
1. Separate the repeating fields into new database tables along with the key from unnormalized
database table.
2. The primary key of new database tables may be a composite key
1NF of above UNF table is as follows:
1. Remove the partial dependencies(A type of functional dependency where a field is only functionally
dependent on the part of primary key) of any non-key field.
2. If field B depends on field A and vice versa. Also for a given value of B, we have only one possible
value of A and vice versa, Then we put the field B in to new database table where B will be primary
key and also marked as foreign key in parent table.
2NF of above 1NF tables is as follows:
Here I am creating a semicolon(;) separated list. You can use comma(,) in place of semicolon to make
comma separated list.
9. Avoid Cursors
Practice to avoid cursor since cursor are very slow in performance. Always try to use SQL Server
cursor alternative. Please refer the article Cursor Alternative.
16. Use Stored Procedure for frequently used data and more
complex queries
Practice to create stored procedure for quaery that is required to access data frequently. We also
created stored procedure for resolving more complex task.
17. Avoid prefix "sp_" with user defined stored procedure name
Practice to avoid prefix "sp_" with user defined stored procedure name since system defined stored
procedure name starts with prefix "sp_". Hence SQL server first search the user defined procedure in
the master database and after that in the current session database. This is time consuming and may
give unexcepted result if system defined stored procedure have the same name as your defined
procedure.
Get nth highest and lowest salary of an employee
One student of me asked "how can we get nth highest and lowest salary on an employee ?". In this
article I am going to expose, how can we achieve this in SQL Server.
Suppose we have employee name and salary as shown in below fig.
Query to get nth(3rd) Highest Salary
1. Select TOP 1Salaryas'3rd Highest Salary'
2. from(SELECT DISTINCT TOP 3SalaryfromEmployee ORDER BY Salary DESC)
3. a ORDER BY Salary ASC
Advance Difference
1. Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function
allows only SELECT statement in it.
2. Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a
SELECT statement.
3. Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT
section whereas Function can be.
4. Functions that return tables can be treated as another rowset. This can be used in JOINs with other
tables.
5. Inline Function can be though of as views that take parameters and can be used in JOINs and other
Rowset operations.
6. Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used
in a Function.
7. We can go for Transaction Management in Procedure whereas we can't go in Function.
Unique Key
By default, Primary key is clustered index and data in the database table is physically organized in the
sequence of clustered index.
In SQL Server, Unique key can be made foreign key into another table.
Primary Key
Foreign Key
Foreign key is a field in the table that is primary key in another table.
By default, Primary key is clustered index and data in the database table is physically organized in the
sequence of clustered index.
Foreign key do not automatically create an index, clustered or non-clustered. You can manually create
an index on foreign key.
Note
As @Marc Jellinek suggested, I would like to add the below points about foreign key :
1. Foreign keys do not automatically create an index, clustered or non-clustered. You must manually create an index on
foreign keys.
2. There are actual advantages to having a foreign key be supported with a clustered index, but you get only one per
table. What's the advantage? If you are selecting the parent plus all child records, you want the child records next to
each other. This is easy to accomplish using a clustered index.
3. Having a null foreign key is usually a bad idea. In the example below, the record in [dbo].[child] is what would be
referred to as an "orphan record". Think long and hard before doing this.
1. IF EXISTS (SELECT * FROM [sys].[schemas][sch] INNER JOIN [sys].[tables][tbl] ON [sch].[schema_id]=[tbl].
[schema_id] WHERE [sch].[name]='dbo' AND [tbl].[name]='child')
2. DROP TABLE [dbo].[child]
3. IF EXISTS (SELECT * FROM [sys].[schemas][sch] INNER JOIN [sys].[tables][tbl] ON [sch].[schema_id]=[tbl].
[schema_id] WHERE [sch].[name]='dbo' AND [tbl].[name]='parent') DROP TABLE [dbo].[parent]
4. CREATE TABLE [dbo].[parent]
5. (
6. [id][int] IDENTITY NOT NULL,
7. [name][varchar](250) NOT NULL,
8. CONSTRAINT [PK_dbo__parent] PRIMARY KEY NONCLUSTERED ([id])
9. )
10. CREATE TABLE [dbo].[child]
11. (
12. [id][int] IDENTITY NOT NULL,[parent_id][int] NULL,
13. [name][varchar](250) NOT NULL,
14. CONSTRAINT [PK_dbo__child] PRIMARY KEY NONCLUSTERED ([id]),
15. CONSTRAINT [FK_dbo__child__dbo__parent] FOREIGN KEY ([parent_id]) REFERENCES [dbo].[parent]([id])
16. )
17. --Insert data
18. INSERT INTO [dbo].[parent]([name]) VALUES ('parent1')
19. INSERT INTO [dbo].[child]([parent_id],[name])VALUES(1,'child 1')
20. INSERT INTO [dbo].[child]([parent_id],[name])VALUES(NULL,'child 2')
21. --Select data
22. SELECT * FROM [dbo].[child]