Click here to Skip to main content
16,017,249 members
Please Sign up or sign in to vote.
4.75/5 (4 votes)
See more: , +
I have a datatable.

I want to perform a Bulk update in such a way that if a record is present in a table then it should be updated, else a new row should be inserted.

Is there any best way to do this in one shot?
Posted
Updated 20-Apr-11 21:55pm
v2
Comments
[no name] 21-Apr-11 0:43am    
hows your table structure?
Dalek Dave 21-Apr-11 3:55am    
Edited for Grammar and Readability.

I think you should bulk insert data in the staging or temp table and then write SQL statements to check for existing records before inserting in the main table.

If you are using SQL 2008, then you can use the new MERGE statement as well.
http://technet.microsoft.com/en-us/library/bb510625.aspx[^]
 
Share this answer
 
Comments
DipaliKolhe 1-May-11 22:01pm    
Thanks Om Prakash Pant!
Try like that

CREATE PROC AlterSomeObj
 @act VARCHAR(10) = 'C',    
 @objXML xml     
AS    
    
IF (@act = 'C')    -- for creating
BEGIN    
    
 INSERT Table1(val1, val2)    
 SELECT     
    
  ITEM.TAB.value('val1[1]','VARCHAR(1000)') AS val1 ,    
  ITEM.TAB.value('val2[1]','VARCHAR(MAX)') AS val2 ,    
  FROM @objXML.nodes('ParentNode/ChildNode') ITEM(TAB)    
    
END    
ELSE IF(@act = 'U')     -- for updating
BEGIN    
 U Table1    
 SET     
 val1 = TAB.val1 ,     
 val2 = TAB.val2,    
    
 FROM     
  Table1 ITEMITEMS    
  INNER JOIN    
  (    
   SELECT    
    ITEM.TAB.value('val1[1]','VARCHAR(1000)') AS val1 ,    
    ITEM.TAB.value('val2[1]','VARCHAR(MAX)') AS val2 
    
   FROM @objXML.nodes('ParentNode/ChildNode') ITEM(TAB)    
  )TAB    
    
 ON ITEMITEMS.ID = @urlID    
   
    
END    
ELSE IF(@act = 'D')    -- for deleting
BEGIN    
--delete logic
END    


As I think it will solve your problem
 
Share this answer
 
Comments
Dalek Dave 21-Apr-11 3:56am    
Good Answer.
Rakshith Kumar 10-Oct-13 23:46pm    
Can we insert a record from microsoft excel and update it in sql server?
nit_singh 21-Apr-11 3:57am    
Thanks Dalek Dave
DipaliKolhe 1-May-11 22:01pm    
Thanks nit_singh

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900