Friday 30 May 2008

STORE PROCEDURE WITH SWITCH

Here's an example of wrapping an update and insert into the same stored procedure.

Let's say your table is called tblContacts with the fields id, FirstName, LastName and Email.

To create a stored procedure which performs both insert and update queries you would use the following syntax:

CREATE PROCEDURE SaveContact(@id int, FirstName varchar, LastName varchar, Email varchar)
as
if id = 0
BEGIN
INSERT INTO tblContacts(id, FirstName, LastName, Email) VALUES(@FirstName, @LastName, @Email)
END
ELSE
BEGIN
UPDATE tblContacts SET FirstName = @FirstName, LastName = @LastName, Email = @Email WHERE id = @id
END

This way you only need to write one method in your Data Access Class.