Wednesday, 15 October 2014

Bulk insert data into table and use cursor to insert data into another table

No comments
ASPX

 protected void Button_Click(object sender, EventArgs e)
        {
            if (fileupload.HasFile == true)
            {
                if (!Directory.Exists(Server.MapPath(@"~\ImportData\")))
                    Directory.CreateDirectory(Server.MapPath(@"~\ImportData\"));
                string path = Server.MapPath((@"~\ImportData\") + importdata.FileName);
                if (File.Exists(path))
                {
                    FileInfo f = new FileInfo(path);
                    f.Delete();
                }
                importdata.SaveAs(path);
                obj.FilePath = path;
                importData.Save(obj);
                importData.Transfer();
                lblMasage.Text = "Record Import Successfully....";
            }
        }

SP FOR   importData.Save(obj);

CREATEprocedure [dbo].[ImportData]       
@FilePath Varchar(500)     
as       
begin        
declare @sql varchar(max)            
set @sql='Truncate table temp'      
exec(@sql)      
set @sql='BULK INSERT temp FROM ''' +@FilePath+''' WITH ( DATAFILETYPE = ''char'', FIELDTERMINATOR =''                  '', ROWTERMINATOR = ''\n'' )'         
exec(@sql)      
End     


SP FOR   importData.Transfer()

CREATE procedure [dbo].[insertTemp]     
as     
begin     
declare @eid int,@dt varchar(30) 
declare chk cursor for      
select EmpId,convert(VARCHAR(30),convert(DATETIME,EmpDate,103),121) from Temp 
open chk      
fetch next from chk into @eid ,@dt      
while @@FETCH_STATUS=0      
begin   
print  @dt   
if not exists(select EmpId from temp1 where EmpId=@eid and EmpDate=@dt )      
begin      
print '1' 
INSERT INTO [temp1](EmpId,EmpDate)      
VALUES ( @eid ,@dt)      
End  
else 
begin 
print '0' 
end     
fetch next from chk into @eid ,@dt    
End      
Close chk      
DEALLOCATE chk     
end