Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate sprocs for Insert/Update or one Set sproc?

So I came across an instance where a stored procedure which handled the Updates on a specific table was doing nothing because the record didn't exist [duh].

So what I decided to do was change the stored procedure to:

 UPDATE    Table
 SET       col1 = @var1
 WHERE     Type = @type AND UserId = @userId 
 IF @@ROWCOUNT = 0
 BEGIN
  INSERT INTO Table
---etc....
 END

So this obviously solved the problem and I renamed the sproc from UpdateTable to SetTable.

Is this a good idea, or should I do something at the application level where if the update returns 0 rows affected, call the insert procedure.

like image 842
Jack Marchetti Avatar asked Dec 30 '25 19:12

Jack Marchetti


2 Answers

I prefer the "upsert" that you have shown because it allows me to stay that much further away from persistence related logic. In the application I just want to work with my objects and "if I must" ask them to save / persist. With update and insert separately you are forced to think about this in the domain model. But the biggest advantage to persistence ignorance is that you can focus on real business problems instead of infrastructure concerns.

This design also helped me migrate to an ORM earlier this year because I didn't have a ton of "update" / "insert" calls, but instead a simple "save"

like image 65
Toran Billups Avatar answered Jan 02 '26 08:01

Toran Billups


I like to have one for each. I makes the sproc perform a specific task instead of two, making it easier to maintain and extend.

like image 44
Chris Love Avatar answered Jan 02 '26 09:01

Chris Love



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!