DNK Gif

Dot Net Knowledge

Labels

Sunday, 5 July 2015

ADO.NET – CONNECTED MODEL

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
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

eg.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 eg.reader["id"]. Alternatively we can provide index we can use reader[0],reader[1] and so on.

eg

// 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

eg int maxUser = Convert.ToInt32(command.ExecuteScalar());

Sample

Create a customer table with id, name, contact number and location. And do the following 

1. Add customer and return the autogenerated 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 seperate 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();

Reference

ADO.NET ppt

VIEWS

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.
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 adminEmployee 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.

Create View adminEmployees

As

Select * from Employees where DeparmentName ='Admin'

with check option

Reference Link

http://www.c-sharpcorner.com/Blogs/10575/advantages-and-disadvantages-of-views-in-sql-server.aspx

INDEXES

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 non- clustered index is just like the index of a book. It contains data sorted so that it’s 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

 CREATE INDEX indexname ON Table (attribute1);

 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/

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 when ever 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:

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:

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.

EXECUTE sp_GetName 9897675412

EXEC sp_updateCustomer 9898978790,'Delhi',5

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

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

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.

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)

insert into tblCustomer

values(@name,@contactNo,@location)

set @id=@@identity

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.

Reference Links

 http://technet.microsoft.com/en-us/library/aa214299(v=sql.80).aspx

 http://msdn.microsoft.com/en-IN/library/ms345415.aspx

 http://msdn.microsoft.com/en-IN/library/ms188927.aspx

Saturday, 4 July 2015

SQL SERVER JOINS

Introduction

SQL joins are used to relate information from different tables. SQL join is used in WHERE clause

of SELECT, UPDATE and DELETE statements.

Various types of joins available in SQL are:

 Inner

 Outer

◦ Left

◦ Right

◦ Full

 Cross Join

 Self Join

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:

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:

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...

RIGHT OUTER JOIN table2

ON table1.common_field = table2.common_field;

Consider the following two tables, (a) CUSTOMERS table is as follows:

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

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:

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:

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:

SQL SUBQUERY

Introduction

  • Subquery or Inner query or Nested query is a query in a query.
  • SQL subquery is usually added in the WHERE Clause of the SQL statement.
  • Generally we use subquery when we know how to search for a value using a SELECT statement, but do not know the exact value in the database.
  • Subqueries are an alternate way of returning data from multiple tables.
  • Subqueries can be used with the following SQL statements along with the comparision operators like =, <, >, >=, <= etc.
◦ SELECT

◦ INSERT

◦ UPDATE

◦ DELETE

Using Subquery in SQL Query :

Lets consider the student_details table which we have used earlier. If you know the name of the students who are studying science subject, you can get their id's by using this query below:

SELECT id, first_name

FROM student_details

WHERE first_name IN ('Rahul', 'Stephen');

but, if you do not know their names, then to get their id's you need to write the query in this manner:

SELECT id, first_name

FROM student_details

WHERE first_name IN (SELECT first_name

FROM student_details

WHERE subject= 'Science');

In the above sql statement, first the inner query is processed first and then the outer query is processed.

Using Subquery in insert statement:

Subquery can be used with INSERT statement to add rows of data from one or more tables to another table. Lets try to group all the students who study 
Maths in a table 'maths_group'.

INSERT INTO maths_group(id, name)

SELECT id, first_name || ' ' || last_name

FROM student_details WHERE subject= 'Maths'

Using Subquery in select statement:

A subquery can be used in the SELECT statement as follows. Lets use the product and order_items table defined in the sql_joins section.

select p.product_name, p.supplier_name, (select order_id from 

order_items where product_id = 101) as order_id from product p where 

p.product_id = 101;

Correlated Subquery

A query is called correlated subquery when both the inner query and the outer query are interdependent. For every row processed by the inner query, the outer query is processed as well. The inner query depends on the outer query before it can be processed.

SELECT p.product_name FROM product p

WHERE p.product_id = (SELECT o.product_id FROM order_items o

WHERE o.product_id = p.product_id);

AGGREGATION OF INFORMATION

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 result-set 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:

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.