Skip to main content

UPSERT (Insert and Update) in SQL Server 2005


In SQL Server 2008 using MERGE concept we can achieve INSERT and UPDATE in a single statement.

Many times we would have faced a scenario like if the key is present in the table then update that record. If the key is not present in the table then insert that as a new record. To do this we normally have to SELECT the record and see whether it EXISTS or not to decide whether to INSERT or UPDATE. The better way which I learnt recently is to make use of @@ROWCOUNT and do this with ease.

Table Structure:

CREATE TABLE tblUpsert
(
EmpID INT PRIMARY KEY,
firstname VARCHAR(25),
lastname VARCHAR(25),
emailid VARCHAR(50)
)
GO

Normal method:

/*
  This SP would work unless it isn't used in multiple threads simultaneously :)
  Same SP is used to INSERT as well as UPDATE a table.
*/
CREATE PROCEDURE uspUPSert
(
@empID INT,
@fname VARCHAR(25),
@lname VARCHAR(25),
@emailid VARCHAR(50)
)
AS
BEGIN
SET NOCOUNT ON


IF EXISTS (SELECT 1 FROM tblUpsert WHERE EmpID = @empID)
BEGIN
  UPDATE tblUpsert
SET emailid = @emailid ,
firstname = @fname ,
lastname = @lname
  WHERE EmpID = @empID
END
ELSE
BEGIN
  INSERT INTO tblUpsert VALUES (@empID, @fname, @lname, @emailid)
END
END
GO

--Testing
EXEC uspUPSert 1, 'Amala','Paul', 'Amala@abc.com'
GO
EXEC uspUPSert 1, 'Amala','Paul', 'AmalaPaul@kollywood.com'
GO
EXEC uspUPSert 2, 'Sachin','Tendulkar', 'Sachin@india.com'
GO
SELECT * FROM tblUpsert
GO

Better or Alternate method to do UPSERT:

/*
Same SP is used to INSERT as well as UPDATE a table.
Here we are avoid unnecessary checking of whether the record exists or not.
Instead try to Update directly. If there is no record then @@RowCount would be 0.
Based on that Insert it as a new record.
*/
CREATE PROCEDURE uspUPSert_Ver2
(
@empID INT,
@fname VARCHAR(25),
@lname VARCHAR(25),
@emailid VARCHAR(50)
)
AS
BEGIN
SET NOCOUNT ON
BEGIN TRAN
UPDATE tblUpsert WITH (SERIALIZABLE)
SET emailid = @emailid ,
firstname = @fname ,
lastname = @lname
WHERE EmpID = @empID

IF @@ROWCOUNT = 0
BEGIN
INSERT INTO tblUpsert VALUES (@empID, @fname, @lname, @emailid)
END
COMMIT TRAN
END
GO

--Testing
EXEC uspUPSert_Ver2 1, 'Amala','Paul', 'Amala@abc.com'
GO
EXEC uspUPSert_Ver2 1, 'Amala','Paul', 'AmalaPaul@kollywood.com'
GO
EXEC uspUPSert_Ver2 2, 'Sachin','Tendulkar', 'Sachin@india.com'
GO
SELECT * FROM tblUpsert
GO

Comments

Popular posts from this blog

My Wedding Anniversary :)

Six years back on the same day I married Sai Lakshmi (12-July-2000). I know Sai for almost 13 years now :) I fell in love with her during my 12th standard. I know @ 17 yrs any person wouldn't be matured enough to make a big decision like this. But thank God my choice was perfect :) Even now, very often we used to think about the past and laugh at our behaviors/actions then. My love story would be really interesting (at least for me and Sai :)) and I am sure none of you guys would be interested in reading about it so lemme not get into it in-depth. But one thing which I want to share is "Without Sai, I wouldn't have entered into the IT field at all". She was instrumental in convincing me to study my Master's degree in Computer Application. That's the move that changed my career. Till my schooling, my dream was to either become a "big" sportsman (Cricket and Badminton were my favorites at that time.) or an Aeronautics engineer. Unfortunately, my l...

Script table as - ALTER TO is greyed out - SQL SERVER

One of my office colleague recently asked me why we are not able to generate ALTER Table script from SSMS. If we right click on the table and choose "Script Table As"  ALTER To option would be disabled or Greyed out. Is it a bug? No it isn't a bug. ALTER To is there to be used for generating modified script of Stored Procedure, Functions, Views, Triggers etc., and NOT for Tables. For generating ALTER Table script there is an work around. Right click on the table, choose "Modify" and enter into the design mode. Make what ever changes you want to make and WITHOUT saving it right click anywhere on the top half of the window (above Column properties) and choose "Generate Change Script". Please be advised that SQL Server would drop actually create a new table with modifications, move the data from the old table into it and then drop the old table. Sounds simple but assume you have a very large table for which you want to do this! Then it woul...

What should one look @ while buying a land in chennai?

Offlate people have started thinking about investing their money in lands. I too think that to be a wise decision only! As most of us know buying a land in chennai (for that matter any where in the world) isn't an easy affair. I was just wondering what all one needs to look at before deciding to purchase a land. I thought I would put down what ever I know about this subject here. [Guys pls free to correct me if I my understanding is wrong somewhere. That way, it would help me understand as well as others who might read this in future]. Here we go ... 1. One should not buy farm lands if they want to build a residential house sometime later there. Because to my knowledge its illegal to build residential houses on lands meant for irrigation. 2. Encumberance Certificate -- This is what is shortly refered as "EC". One needs to get an EC from local sub registrar office (i guess we need pay a small amount for this). From this we / our lawyers :) can find out whether the guy who ...