This is about me and my quest for, er... greater things in life? Good food, good drinks, friends and family and my eternal quest to figure out what I want to do when I grow up. (hint: it's probably going to involve code)

Wednesday, December 17, 2008

SQL separation of concerns

After writing my post last night, I started thinking about ways to remove the bad smell coming out of my SQL code. The issue is that I wrote a stored procedure whose

My thoughts followed this logic:

Well, that's okay. I'll just put an obvious comment in there asking anybody not to change the result set. I'll also rename the stored procedure, ending it with "ForInsert" so that it is obvious what it's for.

Oh man, that is even worse! Now it's like I just sprayed some strawberry fragrance to cover that nasty bathroom smell... You know what I mean!

I guess I could put in some output parameters in my stored procedure instead and use those to insert the data I want. That way, as long as nobody removes a parameter, I'm fine.

Yes, that's better. Compared to my previous thought, this one removes the problem where another programmer would change the order of the fields returned, remove or even add fields in the returned result set. Adding field is the biggest issue here. I know I like to "supplement" stored procedures here and there by adding extra information that is returned to me. Which makes me think...

If I want a stored procedure to return extra data, I'll write another stored procedure that returns the result set of the first one with my extra stuff added to it. That way, I won't break the initial stored procedure.

Hey, I'm learning as I go, Ok? Cut me some slack. I'm going through the usual programming learning curve here. I'm fairly advanced when it comes to regular code like C# or Ruby, but mediocre with SQL. It feels like I just came out of the "Look 'ma! SQL code!" stage and started wondering about encapsulation and separation of concerns. Of course, that is much harder to achieve in SQL than it is in any good object oriented language.

I had one last thought, which I haven't acted upon yet. What about using views and filtering the data on the view instead of passing parameters to a stored procedure? Or what about using common table expression? What about temporary tables? I haven't had time to think those through just yet, but I will...

4 comments:

Anonymous said...
This post has been removed by a blog administrator.
Anonymous said...
This post has been removed by a blog administrator.
Anonymous said...
This post has been removed by a blog administrator.
Anonymous said...
This post has been removed by a blog administrator.