Friday, December 28, 2012

Inserting Multiple Records into Database in one shot

you need to create a Sql Type for the table you will pass in :


CREATE TYPE dbo.DistrictsType AS TABLE
    ( DistrictID int, StoreID int )
and a StoredProcedure that will insert the data from the datatable passed in
CREATE PROCEDURE usp_InsertDistricts 
(@tvpNewDistricts dbo.DistrictsType READONLY)
AS
BEGIN
    INSERT INTO dbo.Districts (DistrictID, StoreID)
    SELECT dt.DistrictID, dt.StoreID FROM @tvpNewDistricts AS dt;
END

then, back to your code you pass the district into the storedprocedure

DataTable dtDistricts = ConvertListToDataTable(Districts);
SqlCommand insertCommand = new SqlCommand("usp_InsertDistricts", sqlConnection);
SqlParameter p1 = insertCommand.Parameters.AddWithValue("@tvpNewDistricts", dtDistricts);
p1.SqlDbType = SqlDbType.Structured;
p1.TypeName = "dbo.DistrictsType";
insertCommand.ExecuteNonQuery();
2nd way to this is by Xml as datatype in store procedure :
ALTER PROCEDURE [dbo].[insertStore]
@XMLDATA xml,
@name varchar(50),
@image datatype
 AS
 Begin
  INSERT INTO Store
  (name
   ,image
  )
Select XMLDATA.item.value('@name[1]', 'varchar(10)') AS Name,   
XMLDATA.item.value('@image[1]', 'yourData type') AS Image
FROM @XMLDATA.nodes('//Stores/InsertList/Store') AS XMLDATA(item)
END

Similarly you can write for update and delete .In C# u need to create the xml
public  string GenerateXML(List<District> Districts)
 var xml = new StringBuilder();
 var insertxml = new StringBuilder();
 xml.Append("<Stores>");
 for (var i = 0; i < Districts.Count; i++)
        { var obj = Districts[i];
          insertxml.Append("<Store");
          insertxml.Append(" Name=\"" + obj.Name  + "\" ");
          insertxml.Append(" Image=\"" + obj.Image + "\" ");
          insertxml.Append(" />");
        }
xml.Append("<InsertList>");
xml.Append(insertxml.ToString());
xml.Append("</InsertList>");

SqlCommand cmd= new SqlCommand("insertStore",connectionString);
cmd.CommandType=CommandType.StoredProcedure;
SqlParameter param = new SqlParameter ();
param.ParameterName ="@XMLData";
param.value=xml;
paramter.Add(param);
cmd.ExecuteNonQuery();

ref:
http://stackoverflow.com/questions/11376498/a-better-way-to-achieve-insert-without-hitting-the-database-multiple-times

No comments:

Post a Comment