3

enter image description here

How can I create a stored procedure to update the Std_Course's column based on the Id and Name parameter, OR inserts a new row if the Id and Name does not exist

4
  • 1
    No need for a stored procedure, just use MERGE Commented Jun 18, 2012 at 7:24
  • @a_horse_with_no_name: that is IF he's on SQL Server 2008 or newer ... MERGE doesn't exist for 2000 or 2005 .... Commented Jun 18, 2012 at 7:25
  • @marc_s: if someone does not mention the version, I assume it's a current one. Commented Jun 18, 2012 at 7:26
  • yes, its SQL Server 2008 Commented Jun 18, 2012 at 7:28

1 Answer 1

3

Try something like this:

CREATE PROCEDURE dbo.proc_InsertOrUpdate @ID INT, @Name VARCHAR(50), @StdCourse INT AS IF EXISTS (SELECT * FROM dbo.YourTable WHERE ID = @ID AND Name = @Name) UPDATE dbo.YourTable SET Std_course = @StdCourse WHERE ID = @ID AND Name = @Name ELSE INSERT INTO dbo.YourTable(ID, Name, Std_Course) VALUES(@ID, @Name, @StdCourse 

Update: since you're on SQL Server 2008, you could also use a simple MERGE statement - either directly "inline" or inside the stored procedure. It would look something like this:

CREATE PROCEDURE dbo.proc_InsertOrUpdate @ID INT, @Name VARCHAR(50), @StdCourse INT AS MERGE dbo.YourTable AS t USING (SELECT @ID, @Name, @StdCourse) AS Source(ID, NAME, Std_Course) ON source.ID = t.ID AND source.Name = t.Name WHEN MATCHED THEN UPDATE SET Std_Course = @StdCourse WHEN NOT MATCHED THEN INSERT(ID, Name, Std_Course) VALUES(source.ID, source.Name, source.Std_Course); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.