-->

Monday, June 9, 2014

How to Optimize Indexes in SQL Server

SQL Server automatically maintains indexes whenever insert, update, or delete operations are made to the underlying data. These modifications cause the information within the index to become scattered in the database. Fragmentation exists when indexes within the index to become scattered in the database.

Fragmentation exists when indexes have pages where the logical ordering does not match the physical ordering within the data file. Heavily fragmented indexes can degrade the query performance and cause your application to respond slowly.

Fragmentation normally occurs when a large number of insert and update operations are performed on the table. Fragmented data can cause the SQL Server to perform unnecessary data reads. This affects the performance of the query. Therefore, index defragmentation is necessary to speed up the query performance.

The first step in deciding which defragmentation method to use is to determine the degree of index fragmentation. You can detect index fragmentation by using the sys.dm_db_index_physical_stats system function.

The following statement displays a list of all the indexes on the HumanResources.Employee table with their fragmentation level:

SELCET a.index_id AS IndexID, name AS IndexName,
Avg_fragmentation_in_percent AS Fragmentation
FROM sys.dm_db_index_physical_stats (DB_ID (N’AdventureWorks’),
OBJECT_ID (‘HumanREsources.Employee’), NULL, NULL, NULL ) AS a
JOIN sys.indexes AS b ON  a.object_id = b.object_id AND a.index_id = b.index_id ORDER BY Fragmentation desc

In the preceding output given by this query, you can notice that the AK_Employee_LoginID index shows a high level of fragmentation.

After the degree of fragmentation is known, the fragmentation needs to be corrected. The following table lists the actions to be taken at different fragmentation levels to defragment the index.

Fragmentation Level                         Action to be Taken
>5% and <=30%  ALTER INDEX REORGANIZE
>30%  ALTER INDEX REBUILD WITH (ONLINE – ON)

Method of Degragmentation

You can execute the following command to defragment the AK_Employee_LoginID index:

ALTER INDEX AK_Employee_LoginID ON HumanResources.Employee REBUILD
After executing the preceding command, the degree of fragmentation is reduced.

Managing indexes with pre-defined Query: SQL Server

In addition to creating indexes in sql server, database developer also need to maintain them to ensure their continued optimal performance. The common index maintenance tasks include disabling, enabling, renaming, and dropping an index. As a database developer, you need to regularly monitor the performance of the index and optimize it.

Disabling Indexes

When an index is disabled, the user is not able to access the index. If a clustered index is disabled then the table data is not accessible to the user. However, the data still remains in the table, but is unavailable for Data Modification Language (DML) operations until the index is dropped or rebuilt.

To rebuild and enable a disabled index, use the ALTER INDEX REBUILD statement or the CREATE INDEX WITH DROP_EXISTING statement.

The following query disables a non-clustered index, IX_EmployeeID, on the Employee table.

ALTER INDEX IX_EmployeeID
ON Employee DISABLE

Enabling Indexes

After an index is disabled, it remains in the disabled state until it is rebuilt or dropped. You can enable a disabled index by rebuilding it through one of the following methods:

  • Using the ALTER INDEX statement with the REBUILD clause
  • Using the CREATE INDEX statement with the DROP_EXISTING clause
  • Using the DBCC DBREINDEX

By using one of the preceding statements, the index is rebuilt and the index status is set to enable. You can rebuild a disabled clustered index, when the ONLINE option is set to ON.

Renaming Indexes

You can rename the current index with the help of the sp_rename system stored procedure.
The following statement renames the IX_JobCandidate_EmployeeID index on the JobCandidate table to IX_EmployeeID.

EXEC sp_rename
‘HumanResources.JobCandidate.IX_JobCandidate_EmployeeID’,
‘IX_EmployeeID’, ‘index’

Dropping Indexes

When you no longer need an index, you can remove it from a database. You cannot drop an index used by either a PRIMARY KEY or UNIQUE constraint, except by dropping the constraint.

The following statement drops the IDX_Employee_ManagerID index on the Employee table:

DROP INDEX IDX_Employee_ManagerID
ON Employee

How to Create Partition Scheme and Clustered Index: SQL Server

After creating the partition function, programmer needs to create a partition scheme to associate it with the partition function. Based on the boundary values defined in the partition function, there will be five partitions. The data of each partition is stored in a filegroup. You should have the same number of filegroups as partitions. If there are five partitions, you need to create five filegroups: fg1, fg2, fg3, fg4, fg5.

The following statements create the PSOrderDate partition scheme, associating it with the PFOrderDate partition function:

CREATE PARTITION SCHEME PSOrderDate
AS PARTITION PFOrderDate
TO (fg1, fg2, fg3, fg4, fg5)

The partition scheme, PSOrderDate, created in the preceding statement directs each partition to a separate filegroup.

Creating a Clustered Index

After creating the partition scheme, you need to associate it with a clustered index. As the clustered index is created on the attribute having unique and non-null values, you can create the index on the SalesOrderID column of the SalesOrderHeader table. To create the partitioned index, you need to associate the clustered index with the partition scheme as follows:

CREATE CLUSTERED INDEX ix_SalesOrderID
ON Sales.MySalesOrderHeader (SalesOrderID)
ON PSOrderDate (OrderDate)

The preceding statement will distribute the table data into five filegroups based on the yearly data of orders stored in the OrderDate column.

How to Create Partitioned Indexes in SQL Server

In SQL Server, indexes can also be partitioned based on the value ranges. Similar to the partitioned tables, the partitioned indexes also improve query performance. Partitioning enables you to manage and access subsets of data quickly and efficiently. When indexes become very large, you can partition the data into smaller, more manageable sections as the data is spread across file groups in a database.

Consider an example. In the Adventure Works database, the SalesOrderHeader table contains the details about the order received by Adventure Works, Inc. As the data in this table is large, the query takes a long time to execute. To solve this problem, you can create a partitioned index on the table. Partitioning an index will distribute the data in the table into multiple filegroups, thereby partitioning the table. This will enable the database engine to read or write data quickly. This also helps in maintaining the data efficiently.

Partitioning is allowed only in the Enterprise Edition of SQL Server. To create a partitioned index, you need to perform the following tasks:

Creating a Partition Function

Similar to creating a partitioned table, you need to create a partition function to create a partitioned index. The partition function will determine the boundary values for creating partitions.

Consider an example. The queries on the SalesOrderHeader table are mostly base on the OrderData column. The sales manager of Adventure Works requires the details of the orders received, on a yearly basis. The table contains the details of orders for the last five years beginning from 2001. Based on this information, you can create a partition function as follows:

CREATE PARTITION FUNCTION PFOrderDate (date time)
AS RANGE RIGHT FOR VALUES (‘2002-01-01’, ‘2003-01-01’, ‘2004-01-01’, ‘2005-01-01’)

The preceding statement creates a partition function, PFOrderDate, by using the date time data type. It specifies four boundary values. Therefore, there will be five partitions. As range right is specified for partitioning, the first partition will contain data less than the first boundary value, 2002-01-01. The second partition will contain data greater than or equal to 2002-01-01 and less than or equal to 2003-01-01. Similarly, other partitions will store data.

Sunday, June 8, 2014

How to bind Gridview using strong model binding in asp.net

In our previous article, we have already learn how to bind GridView using ado.net, Entityframework, etc. Now, today we will learn strong model binding. Follow my steps
Step-1 :  Create a course.cs class, which is include in my previous article
Step-2 : Create a another class, which named as DataContext.cs class also include in my previous article.
Step-3 : After adding the two class in the project , add a new web form, which named as "getItem.aspx".
Step-4 : Add GridView control on web form
Step-5 :  Your source code looking like this

<form id="form1" runat="server">
    <div>
    
    </div>
        <asp:GridView ID="GridView1" runat="server" DataKeyNames ="ID" AutoGenerateColumns="false" ItemType="course" SelectMethod="getCourse">
            <Columns>
                
                <asp:BoundField DataField="ID" HeaderText="Course_Id" />
                  <asp:BoundField DataField="ccode" HeaderText="Course_code" />
                 <asp:BoundField DataField="cname" HeaderText="Course_Name" />


            </Columns>
        </asp:GridView>
    </form>

Here we add two extra attribute, which names as SelectMethod and ItemType. ItemType define the whole structure of your code. Suppose your course class inside in a namespace then your ItemType is
namespace.class name. Using the select method you can retrieve table data from database.

Step-6 : copy this code and paste into your code behind page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class getitem : System.Web.UI.Page
{
    private readonly DataContext dc = new DataContext();
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    public IQueryable<course> getCourse()
    {
        return dc.courses;
    }

}
First to create DataContext object, which is used for retrieving data from database. Also create Select method which return  IQueryable type.

Code generate the following output

How to bind Gridview using strong model binding in asp.net

Saturday, June 7, 2014

How to Bind Gridview using Entity Framework in ASP.NET

In our previous article, we have already learned that how to bind gridview using ado.net. Today we will learn simplest technique to bind gridview using entity framework. Lets start to bind.
Step-1 : Add a Course class with some attributes like

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for course
/// </summary>
public class course
{
    public int ID { get; set; }
    public string cname { get; set; }
    public string ccode { get; set; }

}
In this code ID is the primary key of the table. Learn How to make primary key in entity framework.
Step-2 : Add a DataContext class for creating database with some table like.

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for DataContext
/// </summary>
public class DataContext : DbContext
{
public DataContext():base ("connection1")
{
//
// TODO: Add constructor logic here
//
}
  
    public DbSet<course> courses { get; set; }
}

DataContext class inherit from DbContext class which is inside in System.Data.Entity namespace. Learn How to download it
Here we pass ConnectionString in base class constructor as a parameter. Also add Course table in DataContext using DbSet. 

Step-3 : Add a new webform, which named as "getItem.aspx". Also add a gridView control onit from toolBox.
Step-4 : Add this code in codebehind page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class getitem : System.Web.UI.Page
{
    DataContext dc = new DataContext();
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!Page.IsPostBack)
        {
            bindgrid();
        }
    }

    private void bindgrid()
    {
        var item = from d in dc.courses
                   select d;
        GridView1.DataSource = item.ToList();
        GridView1.DataBind();
        
    }
}

Code Generate the following output

How to Bind Gridview using Entity Framework in ASP.NET

How to download EntityFramework.dll file, Add System.Data.Entity namespace

This namespace take some classes of entity framework for accessing data. In this article we will learn how to add System.Data.Entity namespace because Entity framework.dll missing by default. So first to add entityframework.dll file as a reference.
How to download
Step-1 : Select Package Manager console from Tool menu.

How to download EntityFramework.dll file, Add System.Data.Entity namespace
Step-2 : Write
PM> Install-package entityframework

Note : Internet connection must.
Now, Using this method you can download latest version of entityframework.
© Copyright 2013 Computer Programming | All Right Reserved