Sunday, 9 December 2012

Stored Procedure Insert Update Delete

Creating Table
CREATE TABLE employee(
    id          INTEGER NOT NULL PRIMARY KEY,
    first_name  VARCHAR(10),
    last_name   VARCHAR(10),
    salary      DECIMAL(10,2),
    city        VARCHAR(20),   
 )
Now insert some values in the table and using select statement to select a table.
 INSERT INTO employee VALUES (2, 'Monu',  'Rathor',4789,'Agra');
 GO
 INSERT INTO employee VALUES (4, 'Rahul' ,  'Saxena',   5567,'London');
 GO
 INSERT INTO employee VALUES (5, 'prabhat',  'kumar',  4467,'Bombay');
 go
 INSERT INTO employee VALUES (6, 'ramu',  'kksingh',  3456, 'jk');
 go
 select * from employee
Table looks like this.


Figure 1
Stored procedure for Select, insert, update, delete
Here, we create a stored procedure for select,insert,update,delete statements to select the data from the table.
Alter PROCEDURE MasterInsertUpdateDelete
(
    @id         INTEGER,
    @first_name  VARCHAR(10),
    @last_name   VARCHAR(10),
    @salary      DECIMAL(10,2),
    @city        VARCHAR(20), 
    @StatementType nvarchar(20) = ''
)
AS
BEGIN
IF @StatementType = 'Insert'
BEGIN
insert into employee (id,first_name,last_name,salary,city) values( @id, @first_name,  @last_name,  @salary, @city)   
END

IF @StatementType = 'Select'
BEGIN
select * from employee
END 
IF @StatementType = 'Update'
BEGIN
UPDATE employee SET
            First_name =  @first_name, last_name = @last_name, salary = @salary,
            city = @city
      WHERE id = @id
END
else IF @StatementType = 'Delete'
BEGIN
DELETE FROM employee WHERE id = @id
END
end
Now press F5 to execute the stored procedure.
Now open object explorer and select storeprocedure MasterInsertUpdateDelete.
Stored Procedure to Check Insert
StatementType = 'Insert'
MasterInsertUpdateDelete -> right click select execute stored procedure...

Figure2

Execute procedure window will be open.



Figure3
Now for insert we fill the data in required field.
StatementType=insert


Figure4
Click on the ok Button. and check in the employee table with following inserted data.

Figure5
Stored Procedure to Check update
MasterInsertUpdateDelete -> right click select execute stored procedure...
Execute procedure window will be open.
StatementType = 'Update'


Figure6
Click on the ok Button. and check in the employee table with following updated data where id is 7.

Figure7
Stored Procedure to Check Delete
MasterInsertUpdateDelete -> right click select execute stored procedure...
Execute procedure window will be open.
StatementType = 'Delete'


Figure8
we delete record from table which has id=2
Click on the ok Button. and check in the employee table with following deleted data where id is 2.

Saturday, 8 December 2012

difference between TRUNCATE & DELETE statement in SQL Server

-->Difference between TRUNCATE & DELETE statement in SQL Server -->
TRUNCATE V/s DELETE
Truncate
Delete
TRUNCATE is a DDL command
DELETE is a DML command
TRUNCATE TABLE always locks the table and page but not each row
DELETE statement is executed using a row lock,                                             each row in the table is locked for deletion
Cannot use Where Condition
We can specify filters in where clause
It Removes all the data
It deletes specified data if where condition exists.
TRUNCATE TABLE cannot activate a trigger because the operation does not log individual row deletions.
Delete activates a trigger because the operation                                are logged individually.
Faster in performance wise, because it is minimally logged in transaction log.
Slower than truncate because, it maintain logs for every record


 Drop all object’s statistics and marks like High Water Mark free extents and leave the object really empty with the first extent. zero pages are left in the table
keeps object’s statistics and all allocated space. After a                       DELETE statement is executed,the table can still contain empty pages.
TRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction lo
The DELETE statement removes rows one at a time                       and records an entry in the transaction log for each deleted row
If the table contains an identity column, the counter for that column is reset to the seed value that is defined for the column
DELETE retain the identity
Restrictions on using Truncate Statement
1. Are referenced by a FOREIGN KEY constraint.
2. Participate in an indexed view.
3. Are published by using transactional replication or merge replication.
Delete works at row level, thus row level constrains apply
 

Friday, 7 December 2012

Insert Data more than 1 Table using Transaction

Insert Data more than 1 Table using Transaction


using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using System.Data.SqlClient;



public partial class Default3 : System.Web.UI.Page

{

    SqlConnection cn = new SqlConnection();

    SqlCommand cmd = new SqlCommand();

    SqlTransaction Tr// Create transcation
object

   

  

    DataTable dt = new DataTable();





    protected void Page_Load(object sender, EventArgs e)

    {



    
cn.ConnectionString = @"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated
Security=True;User Instance=True"
;

    
cn.Open();


    }

    protected void Button2_Click(object sender, EventArgs e)

    {

    
Tr = cn.BeginTransaction();
// Begin Transaction

    
cmd.Connection = cn;

     cmd.Transaction = Tr;
// Assign Transaction object value to the command object


    
try    // Try block for Error
checking block


    
{

cmd.CommandText =  
"INSERT INTO employee(eid,ename,epass)VALUES(@eid,@ename,@epass)";

cmd.Parameters.AddWithValue("@eid", TextBox1.Text); // @eid used in insert query;

   
cmd.Parameters.AddWithValue("@ename",TextBox2.Text);
// @ename used in insert query;


    
cmd.ExecuteNonQuery();

        
cmd.CommandText = "INSERT
INTO password(eid,epass)VALUES(@eid,@epass)"
;

        
cmd.Parameters.AddWithValue("eid", TextBox1.Text);

       
cmd.Parameters.AddWithValue("@epass",TextBox3.Text);

        
cmd.ExecuteNonQuery();

        
Tr.Commit();   // Commint
statement save the transcation complete

    

    
}



    
catch (Exception a)  // Cathch block is used for catching the  error type in try block

    
{

        
Tr.Rollback(); // Now rollback statement undo the changes and not saved data

    
}







    }

   

}