Wednesday, April 23, 2008

Easy SQL “If Record Exists, Update It. If Not, Insert It.”

CREATE PROCEDURE dbo.spAddUserName
(
@UserID AS int,
@FirstName AS varchar(50),
@LastName AS varchar(50)
)
AS
BEGIN
DECLARE @rc int

UPDATE [Users]
SET FirstName = @FirstName, LastName = @LastName
WHERE UserID = @UserID

/* how many rows were affected? */
SELECT @rc = @@ROWCOUNT

IF @rc = 0
BEGIN
INSERT INTO [Users]
(FirstName, LastName)
VALUES (@FirstName, LastName)
END

END

1 comment:

Leslie Lim said...

I have found your blogs to be friendly and welcoming. Thanks for making this one. I really enjoy reading and surfing it. Try to visit my site @ www.imarksweb.org

Zea