You are on page 1of 61

.

NET Lounge
Module 5:
Information
Management Basics
Chapter 1: Table creation & Constraints
Chapter 2: Manipulating Information
Chapter 3: Aggregation of Information
Chapter 4: SQL Subquery
Chapter 5: SQL Server Joins
Chapter 6: Stored Procedures
Chapter 7: Indexes & Views
Chapter 8: ADO.NET Connected model
Chapter 9: ADO.NET Disconnected model

Chapter 1: Table creation & Constraints


1.1. Table Creation
Entities are represented as tables in database. The attributes of entities are represented as columns.
As the datas are stored in the attributes of entities the datas are stored in columns in tables. Tables
are organized into rows and columns
For example the Customer entity can be represented as Customer table and the attributes like
Name, Age, Gender, Occupation, Phone, Location, work Experience can be represented as columns
in the table.
Create Table
The CREATE TABLE statement is used to create a table in a database. Create table statement
comes under Data Definition language (DDL)
Syntax
CREATE TABLE Table (Column1 Data type (size), Column2 Data type (size) );
While creating table we need to
Specify the table name
Specify the column names
Specify what type of data each column need to hold (e.g. varchar, integer, decimal, date, etc.).
Specify the size parameter, which the maximum length of the column of the table
Example
Create table Customer (CustomerID int, Name varchar (50), Age int, Gender varchar (10),
Occupation varchar (10));
Alter Table
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
ALTER TABLE also comes under Data Definition language (DDL)
Add Column
Syntax
ALTER TABLE table_name
ADD column_name datatype

Example
ALTER TABLE Customer
ADD Location varchar (50);
Drop Column
Syntax
ALTER TABLE table_name
DROP COLUMN column_name
Example
ALTER TABLE Customer
Drop Location varchar (50);
Change Data Type
Syntax
ALTER TABLE table_name
ALTER COLUMN column_name datatype
Example
ALTER TABLE Customer
Drop Location varchar (30);

1.2. Constraints
Constraints helps to ensure that valid data goes into the database entity by specifying rules.
- NOT NULL: Ensures that attribute cannot be null.
- Primary Key: Represents a column or combination of columns as a unique identity for a row
- FOREIGN KEY: Used to establish relationships between tables using matching columns.
- UNIQUE: The value is unique (not repeated for other entities)
- Check: Used to allow values for a column based on a condition
- Default: Used for inserting default value into columns.
NOT NULL
The NOT NULL constraint will not allow a column to accept NULL values
Below is an example for creating NOT NULL constraint.

Create table Customer (CustomerID int NOT NULL, Name varchar (50) NOT NULL, Age int NOT
NULL, Gender varchar (10) NOT NULL, Occupation varchar (10))
Primary Key
The PRIMARY KEY constraint identifies each record in a database table by allowing only unique
values.
Each table can have only ONE primary key
Below is an example for creating Primary Key constraint.
Create table Customer (CustomerID int NOT NULL Primary Key, Name varchar (50) NOT NULL,
Age int NOT NULL, Gender varchar (10) NOT NULL, Occupation varchar (10))
Primary Key can also be added using alter statement as below
ALTER TABLE Customer
ADD PRIMARY KEY (CustomerID)
Foreign Key
Foreign Key is used to establish relationships between tables using matching columns
A FOREIGN KEY in one table refers to a PRIMARY KEY in another table.
It ensures that data available in the Primary key column of one table can only be entered in the
foreign key column of another table.
Below is an example for creating Foreign Key constraint
CREATE TABLE Orders
(
OrderId int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
CustomerId int FOREIGN KEY REFERENCES Customer (CustomerID)
)
Foreign Key can also be added using alter statement as below
ALTER TABLE Orders
ADD FOREIGN KEY (CustomerId)
REFERENCES Customer (CustomerId)
UNIQUE

UNIQUE Constraint like Primary Key ensures uniqueness for a column. The UNIQUE Constraint is
different from Primary Key in that a table can have only Primary Key but there can be many columns
with Unique Constraint.
Below is an example for creating Unique Constraint
Create table Customer (CustomerID int NOT NULL Primary Key, Name varchar (50) NOT NULL,
Age int NOT NULL, Gender varchar (10) NOT NULL, Occupation varchar (10), Contact int UNIQUE)
Check
Check constraint is used to allow values for a column based on a condition.
Below is an example for creating Check Constraint
We can create a Check Constraint on Age column to allow only values greater than 0.
Create table Customer (CustomerID int NOT NULL Primary Key, Name varchar (50) NOT NULL,
Age int NOT NULL, Gender varchar (10) NOT NULL, Occupations varchar (10), CHECK (Age >0))
Default
Default constraint is used for inserting default value into columns.
Below is an example for creating Default Constraint
We can create a Default Constraint on Location column to enter the default location as 'India' if
location is not inserted while entering Customer details.
Create table Customer (CustomerID int NOT NULL Primary Key, Name varchar (50) NOT NULL,
Age int NOT NULL, Gender varchar (10) NOT NULL, Occupations varchar (10), Location varchar
(20) DEFAULT 'India')

1.3. Problem Scenario


Create database tables for adding employee details such as Employeeid, Employee name, Date of
Joining, Age, Contact number and their salary details such as HRA, Basic, PF, Bonus and Gross
Salary on monthly basis.
Approach to solve the problem
1.

As we need to insert Employee details and their salary details on monthly basis we can create

one table for Employee details and one table for storing Employee Salary details
2.

Create the table Employee with Employee id, Employee name, Date of Joining, Age, Contact

number columns.

3.

Create the table Employee Salary with HRA, Basic, PF, Bonus and Gross

Salary, Salary Date columns.


Solution
Create table Employee (EmployeeID int NOT NULL Primary Key, Name varchar (50) NOT NULL,
Age int NOT NULL, Gender varchar (10) NOT NULL, DateOfJoining Date, Contact int UNIQUE,
CHECK (Age >0))
Create Table EmployeeSalary (SalaryID int NOT NULL Primary Key, Basic int, HRA int, Bonus int,
Gross int, SalaryDate Date, EmployeeID FOREIGN KEY REFERENCES Employee (EmployeeID))
Explanation about the solution
1.

As the Employee Id should be unique and identify each row separately we can

create Employee Id as the Primary Key in Employee table.


2.

We can create a Check Constraint on age and Unique Constraint on Contact in Employee

table.
3.

In Employee salary details create Salary Id as Primary Key and Employee ID as foreign key

referencing Employee Id in Employee table.

Chapter 2: Manipulating Information


2.1. Insert, Delete and Update Statements
Insert
Insert statements are used to insert data into tables.
Syntax
INSERT INTO Table VALUES (attribute value1, attribute value 2 .);
INSERT INTO Table (Coumn1, Column2...) VALUES (attribute value1, attribute value 2 .);
Example:
Insert into Customer VALUES (1,'Customer Name1','Male', 40, 'India')
Insert into Customer (CustomerID, CustomerName, Gender, Age, Location) VALUES (1,'Customer
Name1','Male', 40, 'India')
Update
UPDATE statement helps in modifying database records
Syntax
UPDATE Table set attribute2 = new value WHERE attribute1 = xyz;
Example
Update Customer set age=30 where CustomerID=100
Delete
Delete statement helps in deleting database records
Syntax
DELETE FROM Table WHERE attribute1 = xyz;
Example
Delete from Customer where CustomerID=100;

2.2. Select Statements


Select statements help in selecting data from the database
Syntax
SELECT * FROM Table Name;
Example
SELECT * FROM Customer
Data can be retrieved from the database using different Select options which have been discussed
below
Select statement with projections
Selecting only particular columns from the database
Syntax
SELECT attribute1, attribute2 FROM Table;
Example
SELECT CustomerID, CustomerName from Customer
Select statement with Distinct
Shows the column values by removing the duplicate values.
Syntax
SELECT DISTINCT attribute1 FROM Table;
Example
Select distinct Location from Customer
Select statement with String Functions
String functions such as Upper, Lower, Substring, Char Index can be used in the Select statements
Syntax
SELECT UPPER (attribute1), LOWER (attribute1) FROM Table;
Example
SELECT UPPER (Location) from Customer
Syntax
SELECT SUBSTRING (attribute1, 1, CHARINDEX (' ', attribute1)) FROM Table;

The below example will retrieve the first name from the Customer Name in which the
First and the Last Name are separated by spaces.
Select SUBSTRING (CustomerName, 1, CHARINDEX (' ', CustomerName)) from Customer
The Char Index function returns the position of the space character in Customer
Name. Then using the Substring function we can retrieve the first name by providing the start
position and the position returned by Char Index function.
Select statement with Convert Functions
The Convert function is sued to display the date columns in the table in different styles
Syntax
SELECT CONVERT (data type, attribute1, format) FROM Table;
Example
The below statement will display the Date of Birth in mm/dd/yy format.
Select Convert (varchar (10), DOB, 101) from Customer
Select statement with Filters
Select statements with Filters are used to select records based on condition
1. SELECT statement with WHERE
The filter condition is specified using the WHERE Clause
Syntax
SELECT attribute1 FROM Table WHERE attribute2 = xyz;
SELECT attribute1 FROM Table WHERE attribute2 = xyz AND attribute3 = pqr;
Example
Select CustomerName from Customer where CustomerID > 100;
Select CustomerName from Customer where CustomerID > 100 and CustomerID < 200;
2. SELECT statement with WHERE and IN/NOT IN
This filter is used for checking for matching and unmatched records given a list of values
Syntax
SELECT attribute1 FROM Table WHERE attribute2 IN (pqr, xyz);
SELECT attribute1 FROM Table WHERE attribute2 NOT IN (pqr, xyz);

Example
Select CustomerID, CustomerName from Customer Where Location in ('India', 'US')
Displays the Customer details whose Location is either India or US.
Select CustomerID, CustomerName from Customer Where Location NOT in ('India', 'US')
Displays the Customer details whose Location is neither India nor US.
3. SELECT statement with WHERE and NULL
This filter is used for selecting records for columns with NULL value.
Syntax
SELECT attribute1 FROM Table WHERE attribute2 IS NULL;
Example
Select CustomerID, CustomerName from Customer where Location is NULL
Displays the Customer details whose Location is NULL.
4. SELECT statement with Order By
This filter is used to display the records based on column values either in ascending or descending
order
Syntax
SELECT attribute1 FROM Table ORDER BY attribute1;
SELECT attribute1 FROM Table ORDER BY attribute1 order by desc.
Example
Select CustomerID, CustomerName from Customer order by Location.
Select CustomerID, CustomerName from Customer order by Location desc
5. SELECT statement with Group By
This filter is used for grouping records based on a column value. The column values used for
grouping can be listed using the select statement.
Syntax
SELECT attribute1 FROM Table GROUP BY attribute1;
Example
SELECT Location FROM Customer GROUP BY Location;
In the above example the records in Customer table will be grouped by location values. Suppose we
have locations like India, US, UK, the records will be now grouped under US, UK and India. The

column values used for grouping alone can be displayed using Select. So the above statement will
display only US, UK and India.
6. SELECT statement with Group By and Having
The having clause is used for displaying the column values used in group by clause based on a
condition. In the above example if we want to display the locations which are having a count of more
than 10 employees, then we can go for having clause.
Having clause has to be used along with aggregate functions. Refer to Aggregate functions
documents for understanding on Aggregate functions.
Syntax
SELECT attribute1 FROM Table GROUP BY attribute1 HAVING aggregate_function (attribute1) >
value;
Example
SELECT Location FROM Customer GROUP BY Location having count (Location) > 0
The aggregate function used is the count function.

2.3. Problem Scenario


Insert values into Employee table which has Columns like EmployeeID, Employee Name,
Department, Date of Joining.
Update the Employee name and Department of a particular Employee
Delete an Employee based on Employee Id
Select the Employee based on below criteria
1. Employees of a Department
2. Employees not assigned to department
3. Employees count grouped by department
Approach to solve the problem
1. Insert the values into Employee table using Insert statement
2. Update the Department and Employee name using update statement
3. Delete an Employee using the delete statement by providing the Employeeid in the where
condition
4. List the employees of a department using select with where condition
5. List the employees who have not been assigned to department using null condition
6. List the count of employees using Group By

Solution
Insert into Employee (1, 'Emp1','Finance','09-09-2000')
Update Employee set EmpName ='Emp2', Department='Accounts' where Empid =2
Delete from Employee where Empid= 100
Select * from Employee where Department='Accounts'
Select * from Employee where Department is null
Select count (*) from Employee group by Department
Explanation about the solution
1. Details are inserted using Insert statement.
2. The Department and EmpName has been updated using update statement based on Empid
3. An employee with empid is deleted using delete statements
4. The employees of Department Account have been listed
5. The employees not assigned to any department have been listed using null condition
6. The count of employees of each department is displayed using group by and aggregate function

Chapter 3: Aggregation of Information


3.1. Aggregate Functions
SQL aggregate functions return a single value, calculated from values in a column.
Useful aggregate functions:
AVG () - Returns the average value
COUNT () - Returns the number of rows
FIRST () - Returns the first value
LAST () - Returns the last value
MAX () - Returns the largest value
MIN () - Returns the smallest value
SUM () - Returns the sum
Group By Clause
The GROUP BY statement is used in conjunction with the aggregate functions to group the resultset by one or more columns.
Syntax:
SELECT column_name, aggregate_function (column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;
Example:
SELECT Shippers.ShipperName, COUNT (Orders.OrderID) AS NumberOfOrders
FROM Orders LEFT JOIN Shippers
ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;
The above SQL statement counts as orders grouped by shippers
Having Clause
The HAVING clause was added to SQL because the WHERE keyword could not be used with
aggregate functions.

Syntax:
SELECT column_name, aggregate_function (column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function (column_name) operator value;
Example:
SELECT Employees. LastName, COUNT (Orders.OrderID) AS NumberOfOrders
FROM Orders INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
GROUP BY LastName
HAVING COUNT (Orders.OrderID) > 10;
The above SQL statement finds if any of the employees has registered more than 10 orders:

3.2. Problem Scenario


Write a query to get the employees who has orders more than 25 and their last name should be
either 'Davolio' or 'Fuller'

Approach to solve the problem


Join Employee and Order Table use the aggregate function Count to find the order placed by the

employee and use having clause to filter for the number of order that are more than 25 and use
where clause for filtering based on the last name.
Solution
SELECT Employees.LastName, COUNT (Orders.OrderID) AS NumberOfOrders
FROM Orders INNER JOIN Employees ON Orders.EmployeeID=Employees.EmployeeID
WHERE LastName='Davolio' OR LastName='Fuller'
GROUP BY LastName
HAVING COUNT (Orders.OrderID) > 25;
Explanation about the solution
Employee and Order table is joined using the EmployeeID foreign key in the order table (join
condition here). Then restrict the results only for the employee whose last name is 'Davolio' or 'Fuller'
using a where clause. Then restrict the count of order place using a having clause. Then we have
grouped by the last name.

Chapter 4: SQL Subquery


4.1. Using SubQuery
SQL Subquery
1.1 Objective

Understand SQL Subqueries

Understand Single row, Multiple row and Column Subqueries

Understand Correlated Subqueries

1.2 Introduction

A SUBQUERY is a SQL query nested inside another query.

It is also called as INNER QUERY as it is placed as a part of another query called as MAIN
QUERY / OUTER QUERY.

Subqueries are an alternate way of returning data from multiple tables.

It can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or inside


another subquery.

It is usually added within the WHERE Clause of another SQL statement.

Subquery in a SELECT statement may occur in:

a SELECT clause

a FROM clause

a WHERE clause

Subqueries can be used with the comparison operators such as =, <, >, >=, <=, and also
with the multiple row operators such as IN, ANY or ALL.

Execution Process:

Inner query executes first and passes the result to outer query.

Outer query executes based on the result of inner query.

Syntax:
SELECT select_list
FROM table
WHERE expression comparison_operator
(SELECT select_list
FROM table);

1.3 SubQueries Guidelines

A Subquery must be enclosed in parentheses.

It must be placed on the right side of the comparison operator.

Use comparison operators with single row subqueries.

Inner query should return only one column when comparison operators are used in the outer
query.

The column used in the WHERE clause of outer query should be compatible with the column
information returned by the inner query.

Subqueries cannot manipulate their results internally, therefore ORDER BY clause cannot be
added in to a subquery. ORDER BY clause can be used in the main SELECT statement
(outer query).

GROUP BY and HAVING clauses cannot be used in the inner query when comparison
operators are used in the outer query.

If inner query returns a null value to the outer query, the outer query will not return any rows
when using certain comparison operators in a WHERE clause.

Subqueries that return more than one row can only be used with multiple value operators,
such as the IN operator.

The ntext, text, and image data types cannot be used in the select list of subqueries.

Note: If an error occurs while executing a subquery, execute the inner query
separately to check and fix the error.

1.4 Types of Operators


Following are the operators that can be used in subqueries:
1. Comparison Operators (<, >, <=, >=, =, <>) can be used only when the inner query
returns a single value.
2. List Operators (IN, NOT IN) can be used if the inner query returns a single column with
multiple values.
3. Modified Comparison Operators (ANY or ALL) can be used if the inner query returns
multiple values for outer query evaluation. ANY, ALL operators always used in combination
with comparison operators.
Ex: =any, <any, >any, <all, >all.
4. Existence Operators (Exits or NOT Exists) can be used to check the existence of
records in the inner query, and returns TRUE or FALSE based on the existence of data.
Note: The select list of a subquery introduced with EXISTS, by convention, has
an asterisk (*) instead of a single column name.

1.5 Subquery in SELECT Statement


A Subquery in SELECT statement can be used in a SELECT clause, a FROM clause or a
WHERE clause.
SELECT CLAUSE:
When subquery is used in SELECT clause, it must return a scalar (single) value for each row
returned by the outer query. It is generally used when we wish to retrieve a calculation using an
aggregate function such as the SUM, COUNT, MIN, or MAX function, but do not want the
aggregate function to apply to the main query.
Example: Display the maximum salary of each department.
SELECT d1.dept_name, d1.location,
(SELECT MAX(salary)
FROM tblemployees e1

WHERE d1.dept_no=e1.dept_no) highest_salary


FROM tblDepartment d1
FROM CLAUSE:
A subquery can also be used in the FROM clause to return multiple rows and columns. The
results returned by such a subquery are referred to as a derived table / inline views. A derived
table is useful to work with a subset of data from one or more tables without needing to create a
view or temporary table.
Example: Display the employee details with department name for those whose
department name has letter e.
SELECT emp_id, first_name, last_name, salary, d1.dept_name
FROM tblEmployees e1,
(SELECT dept_no, dept_name
FROM tblDepartment
WHERE dept_name LIKE '%e%')
AS d1
WHERE e1.dept_no=d1.dept_no
WHERE CLAUSE:
Most often, the subquery will be found in the WHERE clause. For instance, different subquery
operators can be used to compare a columns value to a value returned by the subquery.
Single row operator Ex: Use comparison operators such as =, <>, >, <, <=,>=
Display the employee details of Sales Department.
SELECT emp_id, first_name, last_name, salary, designation
FROM tblemployees
WHERE dept_no =
(SELECT dept_no
FROM tblDepartment
WHERE dept_name='sales')

Note: When single row operator is used, and if a subquery returns more than one row
then the query will become invalid and an error will be returned.
Multi row operator Ex: Use IN, ANY, or ALL operator in outer query to handle a subquery that
returns multiple rows.
Display the employee details of Learning and Sales Department.
SELECT emp_id, first_name, last_name, salary, designation
FROM tblemployees
WHERE dept_no IN
(SELECT dept_no
FROM tblDepartment
WHERE dept_name IN ('sales',learning))

1.6 Subquery in INSERT Statement


Subquery can be used with INSERT statement to add rows of data from one or more tables
to another table. Consider a table tblEMPLOYEES_BKP with similar structure as
tblEMPLOYEES table. Lets try to copy employee details of sales department from
tblEMPLOYEES table into tblEMPLOYEES _BKP:
INSERT INTO tblEMPLOYEES_BKP
SELECT * FROM tblEMPLOYEES
WHERE dept_no =
(SELECT dept_no FROM tblDepartment
WHERE dept_name = 'sales')

1.7 Subquery in UPDATE Statement


The subquery can be used in conjunction with the UPDATE statement. Either single or
multiple columns in a table can be updated when using a subquery with the UPDATE
statement.
Example: Update the SALARY by 0.25 times in EMPLOYEES table for
employees working in Sales department.

UPDATE tblEMPLOYEES
SET salary = salary * 0.25
WHERE dept_no =
(SELECT dept_no FROM tblDepartment
WHERE dept_name = 'sales')

1.8 Subquery in DELETE Statement


DELETE statement can be used with subqueries.
Example: Delete the Learning department employee details from EMPLOYEES
table.
DELETE tblEMPLOYEES
WHERE dept_no =
(SELECT dept_no FROM tblDepartment
WHERE dept_name = 'learning')

1.9 Correlated Subquery


A query is called correlated subquery when both the inner query and the outer query are
interdependent. These are used to select data from a table referenced in the outer query.
In correlated subquery, the inner query processing depends on the execution of outer query.
Depending on the results of the correlated subquery execution, it will determine if the row of
the outer query is returned in the final result set.
In this type of queries, a table alias must be used to specify which table reference is to be
used.
Execution Process:

Outer query executes first and passes the result to inner query.

For each row of Outer query result, inner query will be executed.
Display the Departments information where at least one employee is working.
SELECT dept_no, dept_name, location

FROM tbldepartment d1
WHERE EXISTS
(SELECT * FROM tblEmployees e1 WHERE e1.dept_no=d1.dept_no)
Display the list of all employees whose salary is above the average salary for each
employees department.
SELECT emp_id, first_name, last_name
FROM tblEmployees e1
WHERE salary >
(SELECT AVG(salary)
FROM tblEmployees e2
WHERE e1.dept_no=e2.dept_no)

Chapter 5: SQL Server Joins


5.1. Inner Join
The INNER JOIN creates a new result table by combining column values of two tables (table1 and
table2) based upon the join-predicate. The query compares each row of table1 with each row of
table2 to find all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied,
column values for each matched pair of rows of A and B are combined into a result row.
The basic syntax of INNER JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_field =table2.common_field;
Consider the following two tables,
(a) CUSTOMERS table is as follows:

(b) Another table is ORDERS as follows:

Now, let us join these two tables using INNER JOIN as follows:
SQL>SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS
INNER JOIN ORDERS
ON CUSTOMERS.ID =ORDERS.CUSTOMER_ID;
This would produce the following result:

5.2. Outer Joins


Left Outer Join
The SQL LEFT OUTER JOIN returns all rows from the left table, even if there are no matches in the
right table. This means that if the ON clause matches 0 (zero) records in right table, the join will still
return a row in the result, but with NULL in each column from right table.
This means that a left outer join returns all the values from the left table, plus matched values from
the right table or NULL in case of no matching join predicate.

The basic syntax of LEFT OUTER JOIN is as follows:


SELECT table1.column1,table2.column2...
FROM table1
LEFT OUTER JOIN table2
ON table1.common_field =table2.common_field;
Here given condition could be any given expression based on your requirement.
Consider the following two tables,
(a) CUSTOMERS table is as follows:

(b) Another table is ORDERS as follows:

Now, let us join these two tables using LEFT JOIN as follows:
SQL>SELECT ID,NAME,AMOUNT,DATE
FROM CUSTOMERS
LEFT OUTER JOIN ORDERS

ON CUSTOMERS.ID =ORDERS.CUSTOMER_ID;
This would produce the following result:

Right Outer Join


The SQL RIGHT OUTER JOIN returns all rows from the right table, even if there are no matches in
the left table. This means that if the ON clause matches 0 (zero) records in left table, the join will still
return a row in the result, but with NULL in each column from left table.
This means that a right join returns all the values from the right table, plus matched values from the
left table or NULL in case of no matching join predicate.
The basic syntax of RIGHT OUTER JOIN is as follows:
SELECT table1.column1,table2.column2...
FROM table1
RIGHT OUTER JOIN table2
ON table1.common_field =table2.common_field;
Consider the following two tables,
(a) CUSTOMERS table is as follows:

(b) Another table is ORDERS as follows:

Now, let us join these two tables using RIGHT JOIN as follows:
SQL>SELECT ID,NAME,AMOUNT,DATE
FROM CUSTOMERS
RIGHT OUTER JOIN ORDERS
ON CUSTOMERS.ID =ORDERS.CUSTOMER_ID;
This would produce the following result:

Full Outer Join


The SQL FULL OUTER JOIN combines the results of both left and right outer joins.
The joined table will contain all records from both tables, and fill in NULLs for missing matches on
either side.
The basic syntax of FULL OUTER JOIN is as follows:
SELECT table1.column1,table2.column2...
FROM table1
FULL OUTER JOIN table2
ON table1.common_field =table2.common_field;
Here given condition could be any given expression based on your requirement.
Consider the following two tables,
(a) CUSTOMERS table is as follows:

(b) Another table is ORDERS as follows:

Now, let us join these two tables using FULL OUTER JOIN as follows:
SQL>SELECT ID,NAME,AMOUNT,DATE
FROM CUSTOMERS
FULL OUTER JOIN ORDERS
ON CUSTOMERS.ID =ORDERS.CUSTOMER_ID;
This would produce the following result:

5.3. Cross Join and Self Join


Cross Join
The CARTESIAN JOIN or CROSS JOIN returns the Cartesian product of the sets of records from
the two or more joined tables. Thus, it equates to an inner join where the join-condition always
evaluates to True or where the join-condition is absent from the statement.
The basic syntax of CROSS JOIN is as follows:
SELECT table1.column1,table2.column2...
FROM table1,table2 [,table3 ]
Consider the following two tables,
(a) CUSTOMERS table is as follows:

(b) Another table is ORDERS as follows:

Now, let us join these two tables using CROSS JOIN as follows:
SQL>SELECT ID,NAME,AMOUNT,DATE
FROM CUSTOMERS,ORDERS;
This would produce the following result:

Self Join
The SQL SELF JOIN is used to join a table to itself as if the table were two tables, temporarily
renaming at least one table in the SQL statement.
The basic syntax of SELF JOIN is as follows:
SELECT a.column_name,b.column_name...
FROM table1 a,table1 b
WHERE a.common_field =b.common_field;
Here, WHERE clause could be any given expression based on your requirement.
Consider the following two tables,
(a) CUSTOMERS table is as follows:

Now, let us join this table using SELF JOIN as follows:


SQL>SELECT a.ID,b.NAME,a.SALARY
FROM CUSTOMERS a,CUSTOMERS b
WHERE a.SALARY <b.SALARY;
This would produce the following result:

Chapter 6: Stored Procedures


6.1. Create and Execute stored procedures
Stored procedures and its advantages
A stored procedure contains one or more SQL statements that you save so that you can reuse the
code again. So if you have to write query again and again, create stored procedure and then
execute it whenever required the stored procedure.
You can call stored procedure from UI using ADO.Net which we will learn in the next section. You
can have input and output parameters and Executes a series of SQL statements and return the
query results.
Create and Execute stored procedures
Syntax for creating a procedure
CREATE PROCEDURE <Procedure_Name>
-- Add the parameters for the stored procedure here
<@Param1> <Datatype_For_Param1>,
<@Param2> <Datatype_For_Param2>
AS
BEGIN
-- Write statements for procedure here
END
Syntax for executing a procedure
Execute Procedure_Name param1,param2
We can use Execute/Exec to execute a procedure followed by procedure. Provide parameters to
procedures separated by commas. If the procedure does not have any parameter then use Execute
Procedure Name to execute a procedure.
For example, if we have to retrieve name of the customer based on the phone number
SQL SELECT statement
SELECT CustomerName FROM Customer WHERE PhoneNumber = 9897969594;
Procedure is created to replace above query is as follows. Parameters specified where ever
required.

CREATE PROCEDURE sp_GetName


@phoneNo varchar(10)
AS
begin
SELECT CustomerNameFROM Customer
WHERE PhoneNumber = @phoneNo
end
Explanation:
Procedure name is sp_GetName and input parameter to procedure is @phoneNo. All input
parameters/local variables in SQL Server start with @. You can pass one to many parameters to
procedures. Parameters have to be separated by commas
Run the stored procedure:
EXECUTE sp_GetName 9897675412
Stored procedure is executed by execute followed by procedure name and the required input
parameters
Following is another sample which is used to update contact number and location of an employee by
id
create proc sp_updateCustomer
(@contactNo bigint,
@location varchar(30),
@id int)
as
begin
update tblCustomer
set contactNo=@contactNo,Location=@location
where customerid=@id
end
Run the stored procedure:
EXEC sp_updateCustomer 9898978790,'Delhi', 5

In the above statements we have passed values for contact number, location and id when we
execute the procedure. So the required details are updated. You can execute the same procedure
with different values which enables you to reuse the procedure.

6.2. Alter and drop stored procedure


We can alter a stored procedures by simply changing the required query and replacing create by
alter keyword in a procedure.
For eg. Following is the procedure that is view customers
create proc sp_viewCustomer
as
select * from tblCustomer
Now there is a change in the requirement that we have to display the name and location of the
customer. Then just do the following
alter proc sp_viewCustomer
as
select name,location from tblCustomer
Above procedure is modified in a way that it retrieves only name and location of the customer
Now if we have to remove a procedure permanently, we will use the following syntax
drop proc <Procedure_Name>
eg.
drop proc sp_viewCustomer
Output Parameters in Stored procedures
Output parameter is used in stored procedure to return a value to user. out keyword is used for
output parameters. Value should be assigned to the parameter within the procedure.
Eg.
Scenario: To insert customer to customer table and return the auto generated id.
create proc sp_insertCustomer
(@name varchar(30),
@contactNo bigint,

@location varchar(30),
@id int out)
as
begin
insert into tblCustomer
values(@name,@contactNo,@location)
set @id=@@identity
end
Executing a procedure having output parameter
Declare @result int
Execute sp_insertCustomer 'Asha',9898989898,'Mumbai',@id= @result output
Print @result
Explanation:
set @id=@@identity - set keyword is used to do assignment in SQL. @@identity is a global variable
which is used to retrieve the auto generated values. It should be used next to an insert statement.

Chapter 7: Indexes & Views


7.1. Indexes
Indexes are created on columns in tables. The index provides a fast way to look up data based on
the values within those columns. There are two types of indexes: clustered index and non- clustered
index. A Clustered index is the data of table sorted according to the selected columns. A nonclustered index is just like the index of a book. It contains data sorted so that its easy to find, then
once found, it points back to the actual page that contains the data. (In other words, it points back to
the clustered index)
By default primary key column in a table is a clustered index
Syntax:
CREATE INDEX index name ON Table (attribute1);
Eg.
CREATE INDEX ci_ID ON Employee (ID);
Reference Link:
http://www.codeproject.com/Articles/190263/Indexes-in-MS-SQL-Server
https://www.simple-talk.com/sql/learn-sql-server/sql-server-index-basics/

7.2. Views
View is a virtual table. It can contain columns from one or more table .View appears just like a real
table, with a set of named columns and rows of data. SQL creates the illusion like table we can even
insert, update, delete using views
Syntax to create view:
Create view <NameofView>
As
---write select query here
Syntax to execute view:
Select * from <NameOfView>

Eg. Following is the view that retrieves the employees of Admin department. View keyword is used
when creating view.
Create View adminEmployees
As
Select * from Employees where DeparmentName ='Admin'
Executing the view
Select * from adminEmployees
If a view is created from one table then it can also be used to insert, update, delete values to the
table
Insert into adminEmployees Values('Priya','5/5/2010','Admin')
Insert into adminEmployees Values('Puja','5/15/2010','IS')
The above statement will insert value to Employee table.

Chapter 8: ADO.NET Connected model


8.1. ADO.Net
ADO.NET is the managed data access API. .Net data provider provides the facility to interact with
database. It has the classes Reader, Adapter to fetch data from database. It uses connection class
to connect to the database and it uses command class to execute SQL commands.

ADO.Net provides managed types for data access.


Generic types (irrespective of data provider) available in System. Data namespace
SQL Server types in System.Data.SqlClient.

SqlConnection: Used to specify the connection string. Following statement is used to specify
connection string and create an object of SqlConnection
string ConnectionString = "Data Source=ServerName;" + "Initial Catalog=DataBaseName;" + "User
id=UserName;" + "Password=Secret;";

SqlConnection connection = new SqlConnection (ConnectionString);


//Connection is opened using Open method
connection.Open ();
//Connection should be closed after use. Its done using close method
connection.Close ();
SqlCommand: Used to execute SQL Command. Command object is created. Command type can
be text or stored procedure or Table Direct. Command Text is sql query if command type is text. Its
stored procedure name if command type is stored procedure and its table name if command type is
stored procedure.
//create command object
SqlCommand command = new SqlCommand();
//Set command type as stored procedure
command.CommandType = CommandType.StoredProcedure;
//Command text is stored procedure name if command type is stored procedure
command.CommandText = "procedureName";
//Used to relate command object to connection
command.Connection = connection;
SQL Parameter: Used to required add parameters to stored procedure
Following code is used if the procedure has input parameter. Parameter name is specified within
and value is passed to the procedure.
command.Parameters.AddWithValue("@id", id);
Executing command:
Command is executed using following methods
1) ExecuteNonQuery:
Used for insert/update/delete statements. Execute NonQuery returns the number of rows affected
E.g. int rowsAffected = command.ExecuteNonQuery();
2) ExecuteReader:
Used for select query. Execute Reader returns reader object. We use Read method to read from
reader and we can fetch details using reader object. Column name is specified in reader object to

fetch the details of the required column e.g. reader ["id"]. Alternatively we can provide index we can
use reader [0], reader [1] and so on.
e.g.
// Execute procedure with select query
SqlDataReader reader= command.ExecuteReader ();
List<Customer> customerList = new List<Customer> ();
//Read row by row from reader object
while(reader.Read())
{
int id = Convert.ToInt32(reader["id"]);
string name = reader["name"].ToString();
Customer customer = new Customer(id, name);
customerList.Add(customer);
}
3) ExecuteScalar Used when select query returns a single value
E.g. int maxUser = Convert.ToInt32(command.ExecuteScalar());

8.2. Sample
Create a customer table with id, name, contact number and location. And do the following operations
1. Add customer and return the auto generated customer id
2. View all the customers
3. Retrieve contact number for a customer
Following is the sql code for the given scenario
CREATE TABLE tblCustomer(
[customerid] [int] IDENTITY(1,1) primary key,
[name] [varchar](30),
[contactNo] [bigint],
[Location] [varchar](30) )
create proc sp_viewCustomer
as
select * from tblCustomer
create proc sp_viewCustomerbyId

(@id int)
as
begin
select contactNo from tblCustomer
where customerid=@id
end
create proc sp_insertCustomer
(@name varchar(30),
@contactNo bigint,
@location varchar(30),
@id int out)
as
begin
insert into tblCustomer
values(@name,@contactNo,@location)
set @id=@@identity
end
Following is the customer Class
//Customer Class
public class Customer
{
//Attributes
int _customerId;
string _name;
int _contactNo;
string _location;
//properties
public int CustomerId { get { return _customerId; } set { _customerId = value; } }
public string Name { get { return _name; } set { _name = value; } }
public int ContactNo { get { return _contactNo; } set { _contactNo = value; } }
public string Location { get { return _location; } set { _location = value; } }
//constructor
public Customer(int id, string name, int contactNo, string location)
{

_customerId = id;
_name = name;
_contactNo = contactNo;
_location = location;
}
public Customer(string name, int contactNo, string location)
{
_name = name;
_contactNo = contactNo;
_location = location;
}
Following is the customer DB class which contains separate methods for each operation
public class CustomerDB
{
public List<Customer> getCustomers()
{
string ConnectionString = "Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"User id=UserName;" +
"Password=Secret;";
SqlConnection connection = new SqlConnection(ConnectionString);
//Connection is opened using Open method
connection.Open();
//create command object
SqlCommand command = new SqlCommand();
//Set command type as stored procedure
command.CommandType = CommandType.StoredProcedure;
//Command text is stored procedure name if command type is stored procedure
command.CommandText = "sp_viewCustomer";
//Used to relate command object to connection

command.Connection = connection;
// Execute procedure with select query
SqlDataReader reader= command.ExecuteReader();
List<Customer> customerList = new List<Customer>();
//Read row by row from reader object
while(reader.Read())
{
int id = Convert.ToInt32(reader["customerid"]);
string name = reader["name"].ToString();
Customer customer = new Customer(id,
name,Convert.ToInt32(reader["contactNo"]),reader["Location"].ToString());
customerList.Add(customer);
}
//Connection should be closed after use. Its done using close method
connection.Close();
return (customerList);
}
public int geCustomersContactNo(int id)
{
string ConnectionString = "Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"User id=UserName;" +
"Password=Secret;";
SqlConnection connection = new SqlConnection(ConnectionString);
//Connection is opened using Open method
connection.Open();
//create command object
SqlCommand command = new SqlCommand();
//Set command type as stored procedure

command.CommandType = CommandType.StoredProcedure;
//Command text is stored procedure name if command type is stored procedure
command.CommandText = "sp_viewCustomerbyId";
//Used to relate command object to connection
command.Connection = connection;
//Used to pass parameter to procedure
command.Parameters.AddWithValue("@id", id);
// Execute procedure with select query
int number = Convert.ToInt32(command.ExecuteScalar());
//Connection should be closed after use. Its done using close method
connection.Close();
return number;
}
public int addCustomers(Customer custObj)
{
string ConnectionString = "Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"User id=UserName;" +
"Password=Secret;";
SqlConnection connection = new SqlConnection(ConnectionString);
//Connection is opened using Open method
connection.Open();
//create command object
SqlCommand command = new SqlCommand();
//Set command type as stored procedure
command.CommandType = CommandType.StoredProcedure;

//Command text is stored procedure name if command type is stored procedure


command.CommandText = "sp_insertCustomer";
//Used to relate command object to connection
command.Connection = connection;
//Used to pass parameter to procedure
command.Parameters.AddWithValue("@name", custObj.Name);
command.Parameters.AddWithValue("@contactNo", custObj.ContactNo);
command.Parameters.AddWithValue("@location", custObj.Location);
command.Parameters.AddWithValue("@id", 0);
//Denotes that id is a output parameter
command.Parameters["@id"].Direction=ParameterDirection.Output;
//Used to execute command
int rowAffected = command.ExecuteNonQuery();
//Connection should be closed after use. Its done using close method
connection.Close();
// Used to return the value of output parameter
if (rowAffected > 0)
return Convert.ToInt32(command.Parameters["@id"].Value);
else
return (rowAffected);
}

Following is the code executed to be written in main method


CustomerDB db=new CustomerDB();
//Get all customer from getCustomer method in customerDB
List<Customer> customerList = db.getCustomers();
foreach (Customer c in customerList)
{
Console.WriteLine("Customer Id: "+c.CustomerId);
Console.WriteLine("Customer Name: "+c.Name);
Console.WriteLine("Contact Number: "+c.ContactNo);

Console.WriteLine("Location: "+c.Location);
}
Console.ReadKey();
//code to insert a data. You can get data from user
Customer ins=new Customer("Priya",990909090,"Delhi");
int result=db.addCustomers(ins);
Console.WriteLine("Customer Added and id is " + result);
Console.ReadKey();
//code to fetch contact number of customer inserted now
int contactNo=db.geCustomersContactNo(result);
Console.WriteLine(contactNo);
Console.ReadKey();
Query 1:
Select name from Employee
Result:
Priya
Puja
Query 2:
select name from adminEmployees
Result:
Priya
Explanation:

Employee table contains both the employee of all departments but the admin

Employee view displays Employee of admin department.

With Check Option:


If we use with check option when we create view, we can restrict modification to the table based on
the condition specified in the view. That is insert/update/delete is based on the condition specified in
the view.
CreateViewadminEmployees
As

Select*fromEmployees whereDeparmentName ='Admin'


withcheckoption

Chapter 9: ADO.NET Disconnected model


9.1. Disconnected Architecture
ADO.net disconnected model does not require a continuous connection with the database to access
data. Once the data is retrieved from database, it can be accessed even when connection to
database is closed.
ADO.NET Disconnected architecture was built on classes like Connection, DataAdapter,
CommandBuilder, Dataset and DataView. These classes are designed in a way that they
automatically open and close the connection. The data is stored on client-side and is updated in the
database whenever required.
Connection: is used to establish a connection to database. It is required to interact with the
database.

Connection:
Connection c class is used to establish a connection to database. It is required to interact with the
database
DataAdapter:
Data Adapter class is used to transfer the data between database and dataset. It needs a
connection to transfer the data.
CommandBuilder:
Command builder class is used to generate the commands which are not generated by the
DataAdapter automatically, By default, DataAdapter contains only the select command and it doesnt
contain insert, update and delete commands.
DataSet:
Dataset is used to store the data retrieved by data adapter and make it available for .net application.
It provides a consistent relational programming model regardless of the data source.
DataView:
DataView is a view of table available in DataSet. It is used to find a record, sort the records and filter
the records. By using data view, you can also perform insert, update and delete as in case of a
DataSet.

9.2. Data Adapter and Data Set


Data Adapter
DataAdapter is a part of the ADO.NET Data Provider. It provides the communication between the
Dataset and the Datasource. It has commands like select, insert, update and delete.
Following 4 are important properties:
SelectCommand reference to a command (SQL statement / stored procedure name) that
retrieves rows from the data store.
InsertCommand reference to a command for inserting rows into the data store.
UpdateCommand reference to a command for modifying rows in the data store.
DeleteCommand reference to a command for deleting rows from the data store.
Reading and Updating data with Data Adapters:

The adapter supports specific methods to move the data back and forth between the dataset and
data source.
Fill(dsname,tablename):
Opens a connection to database, executes select command, stores the data retrieved by select
command in to dataset and immediately closes the connection.
As connection to database was closed, any changes to the data in dataset will not be directly sent to
the database and will be made only in the dataset.
Update(dsname,tablename):
Transmits changes made to a dataset table to the corresponding database. When it is called, the
DataAdapter will again open the connection to database, executes insert, update and delete
commands to send changes in dataset to database and immediately closes the connection.
Dataset
Dataset is the heart of ADO.NET Disconnected architecture and is presented under System.Data
namespace. It is an in-memory representation of relational data that can store multiple data tables
from multiple data sources. The information in dataset is stored in an XML format.
The structure of a Dataset is similar to that of a relational database; it exposes a hierarchical object
model of tables, rows, columns, constraints, and relationships.

Dataset is of two types: Typed Dataset and Untyped Dataset


Typed Dataset: generates an xsd (xml schema definition) file automatically. It is binded with the
database tables at compile time. So the tables and columns are accessed by the names directly.
Untyped Dataset: It has no corresponding built-in schema. It is binded with the database tables at
runtime. So the tables and columns should be accessed by the index number.

9.3. Steps to access data and perform manipulation


Steps to access data using Disconnected Model
Following steps are used to access data with disconnected model:
1. Define the connection object with appropriate connection string
Syntax:

SqlConnection con
= new SqlConnection (ConfigurationManager .ConnectionStrings[connKey].ConnectionString);
2. Define the data adapter object with Select Command
Syntax:
SqlDataAdapter da = new SqlDataAdapter(select * from employees,con);
3. Define the dataset object
Syntax:
DataSet ds = new DataSet();
4. Fill the dataset object with the result of data adapters query
Syntax:
da.Fill(ds,employees);
5. Read the records from the DataTables in the datasets using the DataRow and DataColumn
objects.
Syntax:
ds.Tables[TableName / TableIndex].Rows[RowIndex][ColumnIndex]
Note: Dataview should be used whenever the data in dataset table has to be sorted, filtered or to be
projected in page wise.
Steps to perform manipulations in Disconnected Model
Following are common steps for data manipulations in disconnected model:
1. Define the connection object with appropriate connection string
Syntax:
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings[connKey].ConnectionString);
2. Define the data adapter object with Select Command
Syntax:
SqlDataAdapter da = new SqlDataAdapter(select * from employees,con);
3. Define the CommandBuilder Object.
Syntax:
SqlCommandBuilder cmb = new SqlCommandBuilder(da);

4. Define the dataset object


Syntax:
DataSet ds = new DataSet();
5. Fill the dataset object with the result of data adapters query
Syntax:
da.Fill(ds,employees);
6. Add a Primary key constraint on the data column of dataset table (optional for insert).
Syntax:
ds.Tables[TableName / TableIndex].Constraints.Add("constraint-name", column _name, true);
Note: CommandBuilder object build the commands for data adapter object based on the primary key
of a table. If the table is defined with a primary key, then all the commands will be generated, else
only
InsertCommand will be generated.
Important methods of Data Row:
1. Contains(PKCOLvalue) : it used to search for a record based on the primary key value. If the
record exists, it returns true otherwise false.
2. Find(PKColValue) : it used to search for a record based on primary key column value. If the
record exists, it returns row object otherwise -1 (error msg).
Steps to search for a record in data table
1. Define a reference variable for the datarow.
Syntax:

DataRow dr;

2. Search for a record in the datatable based on the given value and assign it to the DataRow object.
Syntax:
dr= ds.Tables[TableName / TableIndex].Rows.Find(PKColValue);
3. Retrieve the column values from the DataRow object and display them.
Syntax:
textBoxname.Text=dr["columnname"/ColumnIndex];
Steps to insert the record into the data table:
1. Define the datarow object.
Syntax:

DataRow dr;

2. Assign the new row of the dataset table to the row object
Syntax:
dr= datasetname.tablename.NewRow();
3. Assign the values to the columns of the datarow.
Syntax:
dr[columnname/colindex]=value;
4. Add the data row to the dataset's table.
Syntax:
ds.tablename.Rows.Add(dr);
5. Update the data adapter with the dataset table.
Syntax:
daname.Update(datasetname,tablename);
Steps to Update the record
1. Define the data row object.
Syntax: DataRow dr;
2. Assign the row which has to modified to the datarow object.
Syntax:

dr= ds.Tables[TableName / TableIndex].Rows.Find(pkcolvalue);

3. Call the BeginEdit() on the datarow object.


Syntax:

dr.BeginEdit();

4. Assign the new values for the columns which have to be modified.
Syntax:

dr[colname/colindex]=new value;

5. Call the EndEdit() on the datarow.


Syntax:

dr.EndEdit()

6. Call Update() on the dataadpater to update these changes in the database table.
Syntax:

da.Update(dsname,tablename);

Steps to delete a record


1. Call the delete() on the record which has to be deleted.
Syntax:

ds.Tables[TableName / TableIndex].Rows.Find(pkcolvalue).Delete();

2. Call the Update() on the dataadapter to update the changes in the database table.
Syntax:

da.Update(dsname,tablename);

9.4. Problem Scenario


E-Cognizance Mobile Company is a global mobile manufacturer, whose sales run in tens of
thousands handsets every day, globally. They are providing a default warranty on the phone for one
year. Faults of these handsets are repaired by the manufacturer's Authorized Service Vendor (ASV)
in cities.
The ASV of the E-Cognizance Mobile Company makes the claim for repair and submits for review.
He can also check for the status of the claims based on Claim ID and can update / delete the claim
details, if the Claim Status is submitted.
Following fields are required to work with the Claim Details:
Claim ID - int,
Model number - String,
Model Type ('Basic' / 'Smartphone' / 'Business') - String,
IMEI number (a unique 16-digit number of the mobile phone) - long,
Part Cost - double,
Labor Cost - double,
and Status (Submitted / Accepted / Rejected ) - String.

Approach to solve the problem


1. Create a database table to maintain the Claim Details.
2. Use disconnected model as ASV is the only person who can add, edit, view and delete the claim
details from the database.
3. Retrieve all the Claim Details from database and store it in a Dataset for easy access and to
perform manipulations.
4. When the Claim ID is entered and click on Find button, the claim details should be displayed in
corresponding controls.
5. When new claim details are submitted, it should generate a unique Claim ID and its status should
be updated to Submitted.
6. Editing and deleting the claim details from database should be done based on the Claim ID.
Solution:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
SqlDataAdatper da;
DataSet ds;
Page_Load():
SqlConnection connection = new
SqlConnection(ConfigurationManager.ConnectionStrings["DBCon"].ConnectionString());
adapter = new SqlDataAdapter("Select * from tblClaims", connection);
ds = new DataSet();
adapter.Fill(ds);
ds.Tables[0].Constraints.Add("pk_depid", ds.Tables[0].Columns[0], true);
SqlCommandBuilder cmb = new SqlCommandBuilder(adapter);
btnFind_Click
if (ds.Tables[0].Rows.Contains(txtClaimId.Text))
{
DataRow row = ds.Tables[0].Rows.Find(txtClaimId.Text);
txtModelNo.Text = row[1].ToString();
txtIMEI.Text = row[2].ToString();
-------------

------------}
else
{
txtModelNo.Text = "";
txtIMEI.Text = "";
lblStatus.Text = "No Details found";
}
btnAddNew_Click
txtModelNo.Text = "";
txtIMEI.Text = "";
int lastRowIndex = ds.Tables[0].Rows.Count - 1;
int newClaimId = (int)ds.Tables[0].Rows[lastRowIndex][0] + 1;
txtClaimId.Text = newClaimId.ToString();
txtClaimId.ReadOnly = true;
btnSave_Click
txtClaimId.ReadOnly = false;
DataRow row = ds.Tables[0].NewRow();
row[0] = this.txtClaimId.Text;
row[1] = this.txtModelNo.Text;
row[2] = this.txtIMEI.Text;
ds.Tables[0].Rows.Add(row);
adapter.Update(ds);
lblStatus.Text = "Details are saved successfully";
btnModify_Click
DataRow row = ds.Tables[0].Rows.Find(this.txtClaimId.Text);
row.BeginEdit();
row[1] = this.txtModelNo.Text;
row[2] = this.txtIMEI.Text;
row.EndEdit();
adapter.Update(ds);
lblStatus.Text = "Details are modified successfully";

btnRemove_Click
ds.Tables[0].Rows.Find(this.txtClaimId.Text).Delete();
adapter.Update(ds);
lblStatus.Text = "Details are removed successfully";
this.txtClaimId.Text = "";
this.txtModelNo.Text = "";
this.txtIMEI.Text = "";
}
Explanation about the solution
Step 1: Include all the required namespaces
Step 2: Store the connection string in web.config file because all these actions need to connect to
the same database.
Step 3: DataAdapter and DataSet are declared as Class level members as these are required for
each CRUD operation.
Step 4: As DataAdapter is defined with only Select Command, we cant perform manipulations. So,
CommandBuilder object is used to generate other commands to do manipulations. Primary key is
defined before generating the CommandBuilder object, to generate all Commands.

You might also like