Pages

Tuesday 26 February 2013

SQL Server - Indexes


Relational databases like SQL Server use indexes to find data quickly when a query is processed. 
Creating and removing indexes from a database schema will rarely result in changes to an application's code; indexes operate 'behind the scenes' in support of the database engine. 
The SQL Server engine uses an index in much the same way a reader uses a book index. For example, one way to find all references to INSERT statements in a SQL book would be to begin on page one and scan each page of the book.
 We could mark each time we find the word INSERT until we reach the end of the book. This approach is pretty time consuming and laborious.
 Alternately, we can also use the index in the back of the book to find a page number for each occurrence of the INSERT statements. This approach produces the same results as above, but with tremendous savings in time.

Syntax:
CREATE INDEX [IDX_UnitPrice] ON Products (UnitPrice)
To verify that the index is created, use the following stored procedure to see a list of all indexes on the Products table:
EXEC sp_helpindex Customers 

How It Works
The database takes the columns specified in a CREATE INDEX command and sorts the values into a special data structure known as a B-tree. A B-tree structure supports fast searches with a minimum amount of disk reads, allowing the database engine to quickly find the starting and stopping points for the query we are using.

Advantage of Indexes:

Searching For Records
The most obvious use for an index is in finding a record or set of records matching a WHERE clause. Indexes can aid queries looking for values inside of a range (as we demonstrated earlier), as well as queries looking for a specific value. By way of example, the following queries can all benefit from an index on UnitPrice:
DELETE FROM Products WHERE UnitPrice = 1 
UPDATE Products SET Discontinued = 1 WHERE UnitPrice > 15 
SELECT * FROM PRODUCTS WHERE UnitPrice BETWEEN 14 AND 16 
Indexes work just as well when searching for a record in DELETE and UPDATE commands as they do for SELECT statements.

Sorting Records
SELECT * FROM Products ORDER BY UnitPrice ASC 

Grouping Records
SELECT Count(*), UnitPrice FROM Products GROUP BY UnitPrice

Maintaining a Unique Column
CREATE UNIQUE INDEX IDX_ProductName On Products (ProductName)

Index Drawbacks

  1. Indexes are stored on the disk, and the amount of space required will depend on the size of the table,
  2. Another downside to using an index is the performance implication on data modification statements. Any time a query modifies the data in a table (INSERT, UPDATE, or DELETE), the database needs to update all of the indexes where data has changed.



Type of Indexes in SQL Server - Clustered Indexes & Nonclustered Indexes


Type of Indexes
Clustered Indexes

  1. A common analogy for a clustered index is a phone book. A phone book still sorts entries into alphabetical order. 
  2. The difference is, once we find a name in a phone book, we have immediate access to the rest of the data for the name, such as the phone number and address.
  3. For a clustered index, the database will sort the table's records according to the column (or columns) specified by the index. 
  4. A clustered index contains all of the data for a table in the index, sorted by the index key, just like a phone book is sorted by name and contains all of the information for the person inline. 

create a clustered index:
CREATE CLUSTERED INDEX IDX_SupplierID ON Products(SupplierID) 

  • we can only have one clustered index per table,
  •  In SQL Server, creating a primary key constraint will automatically create a clustered index (if none exists) using the primary key column as the index key.


Non-Clustered Indexes

  1. A book index stores words in order with a reference to the page numbers where the word is located. 
  2. This type of index for a database is a nonclustered index; only the index key and a reference are stored.
  3. The nonclustered indexes created earlier in the chapter contain only the index key and a reference to find the data, which is more like a book index. 

A Disadvantage to Clustered Indexes

  1. If we update a record and change the value of an indexed column in a clustered index, the database might need to move the entire row into a new position to keep the rows in sorted order. This behavior essentially turns an update query into a DELETE followed by an INSERT, with an obvious decrease in performance.
  2.  A table's clustered index can often be found on the primary key or a foreign key column, because key values generally do not change once a record is inserted into the database.

User Defined Functions (UDFs) in SQL Server

User Defined Functions (UDFs)

User defined functions are routines that encapsulates SQL logic inside it. Like stored procedures User defined functions can also be passed input parameters but user defined functions are compiled and executed at runtime so pretty slower than stored procedures.

Certain limitations for User defined functions:

i)  UDF can’t perform DML (data manipulation language) operations like Insertion, Update and Deletion on the base table.

ii) UDF can’t return non deterministic values like GETDATE () etc.

iii) Stored procedure can’t be called from inside a UDF whereas a stored procedure can call a user defined function or another stored procedure inside it.

Syntax:
CREATE FUNCTION dbo.Function
     (
     /*
     @parameter1 datatype = default value,
     @parameter2 datatype
     */
     )
  RETURNS /* datatype */
  AS
     BEGIN
      /* sql statement ... */
     RETURN /* value */
     END
 
Type of UDF :
1) Scalar Functions   (returns a single value)
CREATE FUNCTION EmployeeContactID(@Empid int)
RETURNS int
AS
BEGIN 
Declare @returnvalue int
Select @returnvalue=Employee.ContactID from Employee where Employee.EmployeeID=@Empid
        RETURN   @returnvalue
END
 
Execution:
select dbo.EmployeeContactID(1)
 
2) Inline Functions   (returns a table)
CREATE FUNCTION dbo.GetEmployeeFunction(@empid int)
RETURNS TABLE
AS
RETURN SELECT *
FROM employee where employee.EmployeeID=@empid
 
Execution:
 
select * from dbo.GetEmployeeFunction(1)

Difference between Stored procedures and User defined functions:

i)A stored procedure is pre compiled while a User defined function is compiled and executed at runtime.

ii)A Stored procedure is more flexible than user defined function like you can write complex logic (for example exceptional handling using try catch block is possible in stored procedures which is not possible in user defined functions)

iii) A stored procedure can call another stored procedure or user defined function inside it but a user defined function can’t call stored procedure inside it.

iv)A stored procedure can return non deterministic values but a user defined function can’t return a non deterministic values like Get Date () function.

v) A user defined functions does not support DML operations like insertion, deletion and update on the base table but it is possible via stored procedure.

vi) A user defined function is easier to execute and can be used  inside selection and even for joins but stored procedure can’t be used inside selection queries and it can’t be used to join with other tables.

 

Thursday 21 February 2013

'CASE' in SQL Server


where IsActive =column name
systempostalcode=table name


column IsActive has 1 or 0 values.
we want to return true if IsActive =1, and return false if IsActive =0

select  City, StateCode,  CountryCode, case when IsActive = 1 then 'True' else 'False' end as IsActive   from systempostalcode


Tuesday 19 February 2013

Triggers -- Sql Server


Triggers -- Sql Server

What is a Trigger

  1. A trigger is a special kind of a store procedure that executes in response to certain action on the table like insertion, deletion or updation of data.
  2.  It is a database object which is bound to a table and is executed automatically.
  3.  You can’t explicitly invoke triggers. 
  4. The only way to do this is by performing the required action no the table that they are assigned to.

Types Of Triggers

There are three action query types that you use in SQL which are INSERT, UPDATE and DELETE. So, there are three types of triggers and hybrids that come from mixing and matching the events and timings that fire them.

Basically, triggers are classified into two main types:- 

(i) After Triggers (For Triggers) 
(ii) Instead Of Triggers 

(i) After Triggers

These triggers run after an insert, update or delete on a table. They are not supported for views. 
AFTER TRIGGERS can be classified further into three types as: 

(a) AFTER INSERT Trigger. 
(b) AFTER UPDATE Trigger. 
(c) AFTER DELETE Trigger. 

(a) AFTRE INSERT Trigger

CREATE TABLE Employee_Test
(
Emp_ID INT Identity,
Emp_name Varchar(100),
Emp_Sal Decimal (10,2)
)

INSERT INTO Employee_Test VALUES ('Anees',1000);
INSERT INTO Employee_Test VALUES ('Rick',1200);
INSERT INTO Employee_Test VALUES ('John',1100);
INSERT INTO Employee_Test VALUES ('Stephen',1300);
INSERT INTO Employee_Test VALUES ('Maria',1400);

CREATE TABLE Employee_Test_Audit
(
Emp_ID int,
Emp_name varchar(100),
Emp_Sal decimal (10,2),
Audit_Action varchar(100),
Audit_Timestamp datetime
)
This trigger is fired after an INSERT on the table. Let’s create the trigger as:-
CREATE TRIGGER trgAfterInsert ON [dbo].[Employee_Test] 
FOR INSERT
AS
 declare @empid int;
 declare @empname varchar(100);
 declare @empsal decimal(10,2);
 declare @audit_action varchar(100);

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

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

 PRINT 'AFTER INSERT trigger fired.'
GO

To see the newly created trigger in action, lets insert a row into the main table as : 
insert into Employee_Test values('Chris',1500); 

Concept of View in SQL Server


Concept of View in SQL Server

  1. A view is defined by a query and only shows the data which is defined at the time of creation of the view.
  2.  A view is virtual, the data from a view is not stored physically. 
  3. It is a set of queries that, when applied to one or more tables, is stored in the database as an object.
  4. Views are used for security purpose in the database because it hides the name of the table and logic and provides the virtual table.
  5. A view is used to store the SELECT statement only. In the view we can modify the data and table. 

Syntax of a View

CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition

Example

create view stud
as  select studname,studid,studaddress
from student where depno='d001'

SQL SERVER – Introduction to JOINs – Basic of JOINs

INNER JOIN

This join returns rows when there is at least one match in both the tables.




SELECT t1.*,t2.*
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.ID = t2.ID

SQL SERVER – Introduction to JOINs – Basic of JOINs

LEFT OUTER JOIN

This join returns all the rows from the left table in conjunction with the matching rows from the right table. If there are no columns matching in the right table, it returns NULL values.


SELECT t1.*,t2.*
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.ID = t2.ID

SQL SERVER – Introduction to JOINs – Basic of JOINs

RIGHT OUTER JOIN

This join returns all the rows from the right table in conjunction with the matching rows from the left table. If there are no columns matching in the left table, it returns NULL values.



SELECT t1.*,t2.*
FROM Table1 t1
RIGHT JOIN Table2 t2 ON t1.ID = t2.ID
WHERE t1.ID IS NULL

SQL SERVER – Introduction to JOINs – Basic of JOINs

CROSS JOIN

This join is a Cartesian join that does not necessitate any condition to join. The resultset contains records that are multiplication of record number from both the tables.


SELECT t1.*,t2.*
FROM Table1 t1
CROSS JOIN Table2 t2



Sunday 17 February 2013

How can find out all Store Procedure in your database by query?


select * from  sysobjects where xtype='P'


How can find out all modify Store Procedure in your database by query?


SELECT name,modify_date,*

FROM sys.objects

WHERE type = 'P'

AND DATEDIFF(D,modify_date, GETDATE()) < 1


How can find out all function in your database by query?


select * from  sysobjects where xtype in ('FN','IF','TF')

Convert Date-Time format in SQL Server


Convert Date-Time format in SQL Server

SELECT CONVERT(VARCHAR(20), GETDATE(), 100)
Feb 18 2013 11:29AM (Mon DD YYYY HH:MM AM/PM)
SELECT CONVERT(VARCHAR(20), GETDATE(), 101)
02/18/2013 (MM/DD/YYYY)
SELECT CONVERT(VARCHAR(20), GETDATE(), 102)
2013.02.18 (YYYY.MM.DD)
SELECT CONVERT(VARCHAR(20), GETDATE(), 103)
18/02/2013 (DD/MM/YYYY)
SELECT CONVERT(VARCHAR(20), GETDATE(), 104)
18.02.2013 (DD.MM.YYYY)
SELECT CONVERT(VARCHAR(20), GETDATE(), 105)
18-02-2013 (DD-MM-YYYY)
SELECT CONVERT(VARCHAR(20), GETDATE(), 106)
18 Feb 2013 (DD Mon YYYY)
SELECT CONVERT(VARCHAR(20), GETDATE(), 107)
Feb 18, 2013 (Mon DD, YYYY)
SELECT CONVERT(VARCHAR(20), GETDATE(), 108)
11:37:14 (HH:MM:SS)
SELECT CONVERT(VARCHAR(20), GETDATE(), 109)
Feb 18 2013 11:37:53 (Mon DD YYYY HH:MM:SS)
SELECT CONVERT(VARCHAR(20), GETDATE(), 110)
02-18-2013 (MM-DD-YYYY)
SELECT CONVERT(VARCHAR(20), GETDATE(), 111)
2013/02/18 (YYYY/MM/DD)
SELECT CONVERT(VARCHAR(20), GETDATE(), 112)
20130218 (YYYYMMDD)
SELECT CONVERT(VARCHAR(20), GETDATE(), 113)
18 Feb 2013 11:40:18 (DD Mon YYYY HH:MM:SS)
SELECT CONVERT(VARCHAR(20), GETDATE(), 114)
11:40:54:040 (HH:MM:SS:MMM)24 hr
SELECT CONVERT(VARCHAR(20), GETDATE(), 120)
2013-02-18 11:53:32 (YYYY-MM-DD HH:MM:SS)

-- we can also use as follow

SELECT SUBSTRING(CONVERT(VARCHAR(10), GETDATE(), 120), 3, 8) AS [YY-MM-DD]
13-02-18 (DD-MM-YYYY)
SELECT REPLACE(CONVERT(VARCHAR(8), GETDATE(), 11), '/', '-') AS [YY-MM-DD]
13-02-18 (DD-MM-YYYY)


Tuesday 12 February 2013

Duplicate Records in SQL Server


see the record without duplicate value

select name,emp_id,City from MyTable

Count Duplicate Records

Syntax:
SELECT YourColumn, COUNT(*) TotalCount
FROM YourTable
GROUP BY YourColumn
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC

Example:
SELECT name, 
 COUNT(email) 
FROM users
GROUP BY email
HAVING ( COUNT(email) > 1 )

Delete Duplicate Records – Rows multipul column


DELETE
FROM MyTable
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM MyTable
GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn3 HAVING COUNT(*)>1))


Delete Duplicate Records – Rows Single column


DELETE
FROM MyTable
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM MyTable
GROUP BY DuplicateColumn HAVING COUNT(*)>1))



Monday 11 February 2013

How to fetch data from Excel file to Data Set in ASP .Net


 protected void Page_Load(object sender, EventArgs e)
    {


        if (!IsPostBack)
        {
            GenerateExcelData();
        }
    }


private void GenerateExcelData()
    {
        try
        {
            OleDbConnection oledbConn;
            string path = System.IO.Path.GetFullPath(@"C:\Users\user\Desktop\PriceAnalysis.xls");
            oledbConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
           path + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
         
            oledbConn.Open();
            OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet2$]", oledbConn);
            OleDbDataAdapter oleda = new OleDbDataAdapter();
            oleda.SelectCommand = cmd;
            DataSet ds = new DataSet();
            oleda.Fill(ds, "Table");
            //return ds.Tables[0];
        }
        catch
        {
            //return null;
        }
       

    }
}

Note : where Sheet2 is your sheet name.

Friday 8 February 2013

How can use Split function in C#


I want split 2009-2010 in year format like: 2009

INPUT :   2009-2010  (financialYear)

OUTPUT: 2009


  char[] splitter1 = { '-' };
            string[] year1 = financialYear.Split(splitter1);
            int str1 = Convert.ToInt32(year1[0].ToString());
          
str1 give result: 2009

How to find list of recently execute store procedure



Select DB_Name(dest.[dbid]) As 'databaseName'
   , Object_Name(dest.objectid) As 'procName'
   , Max(deqs.last_execution_time) As 'last_execution'
From sys.dm_exec_query_stats As deqs
Cross Apply sys.dm_exec_sql_text(deqs.sql_handle) As dest

Group By db_name(dest.[dbid])
   , Object_Name(dest.objectid)
Order By databaseName
   , procName
Option (MaxDop 1);


Wednesday 6 February 2013

how to show data in GridView - nice and simple code


 using dataset

add connection string in web config :

<connectionStrings>
<add name="ConnectionString" providerName="System.Data.SqlClient" connectionString="Data Source=USER-PC\SQLEXPRESS;Initial Catalog=master;User id= sa;Password=sa"/>
</connectionStrings>

in .cs page :
string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString(); SqlConnection con = new SqlConnection(str); con.Open(); string s = "select * from employee"; SqlDataAdapter adp = new SqlDataAdapter(s, con); DataSet ds = new DataSet(); adp.Fill(ds, "dataset"); GridView1.DataSource = ds; GridView1.DataBind(); con.Close();

or
SqlConnection con=new SqlConnection(<mention here your connectionstring>);
con.Open();
SqlCommand cmd=new SqlCommand("select * from sam",con);
\\where 'rohit' is table name
SqlDataReader dr=cmd.ExecuteReader();
DataTable dt=new DataTable();
dt.Load(dr);
GridView1.DataSourece=dt;
GridView1.DataBind();
con.Close();