Frans Bouma's blog

Generator.CreateCoolTool();

Syndication

News




    Add to Technorati Favorites

About me

Fun stuff I created

My work

Stored procedures are bad, m'kay?

Let me start with a blunt statement: stored procedures are bad, they are a bad way to formulate data-access logic. I can't state that enough. Today I stumbled into a blog by Rob Howard, which tries to convince the reader that whatever you do, use stored procedures! With tears in my eyes I've read the arguments he brings to the table. Some are silly and one is even based on completely wrong information and assumptions and so far away from the truth it hurts. I've blogged about stored procedures before (here, here and here) and I used them a lot for 8 years, but I'm now almost stored procedure 'free' for 8 months now, and I love the feeling. The reason is obvious: the stress of maintaining a lot of stored procedures, to write another stored procedure for each thing you want to do, is gone. Dynamic SQL is the future. (Dynamic SQL is generated on the fly by a generic piece of code which gets various data as input and generates a parametrized query from it. Which can be cached on the client and will be cached on the server. Dynamic SQL generated based on objects written in C# or VB.NET).

Let's walk through Rob's list of arguments and see what we can make out of it. Let me start by saying that Rob's list of arguments is the default list of arguments any DBA will offer you when you ask him/her why stored procedures are better. However, keep in mind that the DBA most likely will offer you that list to save his/her job.

  • Ad-hoc SQL Script is brittle
    Sure, it is generated on the fly, it is gone when it is executed (except for the execution plan, Rob, but more on that later). Rob comes with the argument that putting ad-hoc SQL in your BL code is not that good. Agreed, but who said that there is just one other option to solve that problem and that option is stored procedures? ... small changes to the database can have severe impacts on the application. Yes, that's right, however changes to a relational model will have always an impact on the application that targets that model: add a non-nullable column to a table. You can use stored procedures or ad-hoc queries, you have to change the calling code to make sure that column gets a value when a new row is inserted. For Ad-hoc queries, you change the query, and you're set. For stored procedures, you have to change the signature of the stored procedure, since the INSERT/UPDATE procs have to receive a value for the new column. This can break other code targeting the stored procedure as well, which is a severe maintenance issue. A component which generates the SQL on the fly at runtime, doesn't suffer from this: it will for example receive an entity which has to be saved to the database, that entity contains the new field, the SQL is generated and the entity is saved. No maintenance problems. With a stored procedure this wouldn't be possible.
  • Security
    Ah yes, the good old dead horse, security! The most heard argument in favor of stored procedures is that with using stored procedures, security can be controlled using a fine grained mechanism: place the execution rights on the procedure and you're set. Well... ever heard of role-based security? Rob Howard hasn't obviously. Security is a subject that has to be taken seriously, very seriously. Therefore, a good DBA defines user-roles in SqlServer. Users are added to those roles and rights are defined per role, not per user. This way, you can control which users can insert / update and which users can for example select or delete or have access to views in an easy way: in most applications you have 2 roles: the average user, and the administrator user which configures the application. Define 2 roles in the SqlServer database, place the users in the right role, define the rights per role on the tables and views and off you go: fine grained security which works, without a single stored procedure in sight. A new user is added? You just add it to a user role and it has the rights it should have.
    Another nice object in SqlServer, which I already mentioned earlier, is the view. Views are there to control which data is accessed on a column basis or row basis. This means that if you want user U to select only 2 or so columns from a table, you can give that user access to a view, not the underlying table. The same goes for rows in one or more tables. Create a view which shows those rows, filtering out others. Give access rights to the view, not the table, obviously using user-roles. This way you can limit access to sensitive data without having to compromise your programming model because you have to move to stored procedures. Views are totally ignored by Rob Howard, while the view is especially created for this purpose. See Books Online: Using Views as Security Mechanisms.
    Rob mentions SQL injection attacks. SQL queries which are constructed by simply concatenating data into a query statement are indeed open for SQL injection attacks. However because ADO.NET has a great parameter support, why would anyone neglect this fine instrument? A good Dynamic SQL engine creates parametrized queries, which are not only faster (because the execution plan is cached, yes Rob, it is), they are also not open for SQL injection attacks due to the parameters.
  • Performance
    Everyone who thinks stored procedures are pre-compiled, say "Aye!". Whoa, what a noise! For all of you who said "Aye!" a few seconds ago: open SqlServer's Books Online (v7 or v2000, doesn't matter), search for "cache execution plan". You'll find fine articles like "Execution Plan Caching and Reuse" and "SQL Stored Procedures". Let me just quote some lines from the "SQL Stored Procedures" article:
    SQL Server 2000 and SQL Server version 7.0 incorporate a number of changes to statement processing that extend many of the performance benefits of stored procedures to all SQL statements. SQL Server 2000 and SQL Server 7.0 do not save a partially compiled plan for stored procedures when they are created. A stored procedure is compiled at execution time, like any other Transact-SQL statement. SQL Server 2000 and SQL Server 7.0 retain execution plans for all SQL statements in the procedure cache, not just stored procedure execution plans.
    I didn't make that up, people. It's there, for a long time (since SqlServer 7.0).
    However, what does Rob Howard say? I quote:
    There are also internal performance benefits to SQL Server for using stored procedures vs. ad-hoc SQL script. When stored procedures are used SQL Server can cache or pre-compile the ‘execution plan’ that it uses to execute the SQL vs. having to recalculate the execution plan on each request.
    Isn't that a little wrong, Rob? There is no precompilation of stored procedure code in SqlServer. It caches execution plans for each query, also ad-hoc queries. Even better: it will parametrize queries which don't even have parameters to keep the execution plan in the cache!
    Rob also claims that you can better loop through rows in T-SQL (in 'many cases') than in the data-access layer because doing it in T-SQL is faster (according to Rob). Now, looping through rows in T-SQL requires a cursor. A cursor will always create a temp table in tempdb, which can hurt performance pretty bad if tempdb is full and has to be resized. Doing a lot of looping will require that sooner or later. Besides that, T-SQL is not a procedural language, it's a set-based language (© Joe Celko). This means that the only power T-SQL has over procedural languages is that it can work on sets of data very fast. Looping through a resultset means that you didn't understand what set-based means or what you want can't be done in a set-based batch of statements. It's then better to choose the best language for the procedural statements instead of using a set-based language for this and feed it the least amount of data to perform its task.
    Now, let me add something about performance here. Say, you have a database with 100 tables, with an average of 7 fields per table. This requires 100 update stored procedures, at least (the crUd procs). These 100 procedures will have on average 7 parameters to update all fields at once, because you can't create optional update statements in stored procedures. You can't create stored procedures for all possible combinations either, that would require 100*7! procedures, which is quote a lot. A component which will create the SQL on the fly will tailor the UPDATE query to the job it has to do, for example updating that single varchar field in a row with 2 blob fields. The blob fields aren't passed to the database again, because that field isn't updated. Another nice thing about creating SQL on the fly is that you can create the WHERE predicate on the fly. Foreseeing every possibly WHERE predicate for an UPDATE stored procedure is undoable. You can fall back to optional parameters, but that will do you no good either, because COALESCE isn't that great when it comes to performance. (see my previous blogs about dynamic SQL and stored procedures).

Stored procedures also will open up a maintenance problem. The reason for this is that they form an API by themselves. Changing an API is not that good, it will break a lot of code in some situations. Adding new functionality or new procedures is the "best" way to extend an existing API. A set of stored procedures is no different. This means that when a table changes, or behaviour of a stored procedure changes and it requires a new parameter, a new stored procedure has to be added. This might sound like a minor problem but it isn't, especially when your system is already large and runs for some time (when it becomes 'legacy' but the amount of time and money invested in the system is that huge that replacing it will cost more than altering the current system). Every system developed runs the risk to become a legacy system that has to be maintained for several years. This takes a lot of time, because the communication between the developer(s) who maintain/write the stored procedures and the developer(s) who write the DAL/BL code has to be intense: a new stored procedure will be saved fine, however it will not be called correctly until the DAL code is altered. When you have Dynamic SQL in your BL at your hands, it's not a problem. You change the code there, create a different filter, whatever you like and whatever fits the functionality to implement. A good O/R mapper helps you with this. Microsoft also believes stored procedures are over: Microsoft's next generation business framework MBF is based on Objectspaces, which generates SQL on the fly.

I too find writing code like string s = "SELECT * FROM Foo WHERE Bar = " + barValue; in your code not the right thing to do. However the alternative is not stored procedures, it's a component that generates this SQL on the fly so you don't have the disadvantages of stored procedures and have the advantages of generating the SQL you need. Writing such a component is a one-time effort, you can reuse that component each time you access a database. Stored procedures are not the answer, Dynamic SQL is.

Published Tuesday, November 18, 2003 12:33 PM by FransBouma

Comments

# Stored Procedures versus Dynamic SQL - the old debate...Frans Bouma's take...@ Tuesday, November 18, 2003 1:11 AM

TrackBack

# Why stored procudures can be evil?@ Tuesday, November 18, 2003 2:11 AM

TrackBack

# Stored Procedures@ Tuesday, November 18, 2003 2:33 AM

TrackBack

# Stored procedures vs Dynamic SQL@ Tuesday, November 18, 2003 2:53 AM

TrackBack

# Stored Procedures or not?@ Tuesday, November 18, 2003 3:20 AM

TrackBack

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 6:57 AM

My words :-)

Thomas Tomiczek

# ASP.NET dynamic SQL vs. stored procedures - what's right?@ Tuesday, November 18, 2003 6:58 AM

TrackBack

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 7:42 AM

Sorry Frans - I have to respectfully disagree, life without Stored Procedures is silly.

Duane

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 7:49 AM

Duane: can you elaborate on that a bit? Just stating it's silly great but not a solid argument.

That said, I write a stored procedure sometimes, the last one I wrote was a sequence emulator stored procedure. However the occasions I have to are countable on one hand, while I do database development every day.

Frans Bouma

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 8:10 AM

All I can say is that I respectfully disagree 150%! Stored Procedures do provide a dramatic performance boost over dynamic SQL when needed. A generic DB access component is a disaster waiting to happen, as it depends on a properly designed database, which no one will ever create.

Wally

Wallym

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 8:17 AM

Taking a binary approach is silly, you can't sriously be saying that for every occasion dynamic Sql is better - a few instances where I disagree - Indexed Views, these are essentially SPs, and are invaluable in a scalable environment (Indexed views representing an essentially 'static' view on data, updated when the underlying data is). Using Table Variables in SQL Server 2000 from Stored Procedures lets me composite and filter my resultset before returning it to the client app thereby substantially reducing my network traffic, connection usage, memory footprint for the app and therefore vastly increasing my potential scalability. Your argument about using Views is pretty limited in my opinion, Views are not updatable, I can't get a resultset from one SP and based on that, update the data in my view then filter the data in my View to produce the desired resultset - even if I could, I would be storing a HUGE resultset for many operations where I only require a couple of items - Views cannot replace SPs in most circumstances.
Quite simply, I also do serious web application development every single day, 99% of requests to the DB are best served by stored procedures, I have worked a lot with Dynamic SQL in code previously (forced to when using MySQL with PHP / Java), the risk of introducing errors into really quite complex Dynamically built SQL statements is really pretty high - plus it's pretty tricky to debug every possible scrnario unde which the statement may be built.

Scott Galloway

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 8:20 AM

Wallym: the dramatic performance boost is not there, because the stored procs are threated as queries which arrive at the sql engine: they are compiled at runtime.

So they're not faster, they are sometimes even slower, because you have to code constructs in the stored proc to add some sort of flexibility (like a bit parameter which is used in an IF ELSE clause. That will force a recompile every time!).

Don't believe the myth, read the docs (Books Online). They're clear on this.

Frans Bouma

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 8:26 AM

::All I can say is that I respectfully
::disagree 150%!

Ah, kids playing.

Look, how can you disagree when the documentation says rob is wrong?

How can you disagree for arguments given when you basicaly have NO arguments.

::Stored Procedures do provide a dramatic
::performance boost over dynamic SQL when
::needed

Factually total bullshit.

Stored Prcedures CAN provide a significant performance boost in certain situations when you are able to move processing fom the application layer to the database. Not "when needed" as you say, but "when needed AND when the data processing fits into this condition".

Stored Procedures are NOT significantly faster than dynamic SQL if all the Stored Procedure does is a single INSERT/UPDATE/DELETE.

This is another fact that is well documented (in this little thing called documentation).

::A generic DB access component is a disaster
::waiting to happen, as it depends on a
::properly designed database, which no one
::will ever create.

Careless use of SP's are a desaster HAPPENED. Get this - the generic component may be a desaster waiting to happen, but having hundreds of objects that require some gpoor guy to create and maintain hundreds of methods that are nothing more than simple processing IS A DESASTER THAT HAPPENED.

By the time this poor sould is finished with his little task, other people have already finished the complete application.

SP's are VERY nice in a lot of situations, and every generic layer COULD utilize them actually (not a lot now, but definitly a lot more once YUKON is around). But stating "they are better. Period" is not a sign for maturity at all.

Counter the arguments Frans has put up, or realize that you dont have any good arguments at all.

Thomas Tomiczek

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 8:29 AM

Indexed views can be accessed as normal views, by normal SQL. Views are something else than a stored procedure, Scott. Also your argument about connection usage is odd: connection pools will serve you well.

True, it requires some work to get a dynamic query generator right, but once you have one, you don't have to recode it again.

"I can't get a resultset from one SP and based on that, update the data in my view then filter the data in my View to produce the desired resultset - even if I could, I would be storing a HUGE resultset for many operations where I only require a couple of items - Views cannot replace SPs in most circumstances. "
Views are used to control the security issues. SP's are code-statements, views can be seen as static tables, for SELECT statements, FROM clauses and WHERE predicates. you can for example update rows in a table using the FROM clause to filter on a view's data. Views aren't limited, they are as flexible as tables, because they are a view on tables, replacing those tables in logic which would otherwise be performed on the tables. Views don't replace update stored procedures, they can be used to control security where sp's are used to do that.

Frans Bouma

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 8:36 AM

sprocs performance increase isn't just due to the precompilation. It is also due to the reduction of round tripping to the client (which isn't cheap), and reduction of network traffic that comes with it (ahh, good times).

As for the security mechanisms, I do a lot of training with healthcare and government bodies, and regulations require them to not give developers access to the underlying tables. Period. I guess you could use views for everything, but you'll have to be writing after triggers to get that to work and at that point you might as well be writing stored procedures anyways.

And most people are doing security for more than two roles. If you are doing security on a column basis for even just five roles, may god have mercy on your soul. You will screw up, you will waste time and you will end up opening more data to people that don't need it. Just like security based on roles is easier to implement, security based on tasks is also easier to maintain and implement.

Of course, that's just my opinion, I could be wrong. It's interesting to see everyone else's opinion on the subject though.

Phil Scott

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 8:42 AM

Phil...the round trip argument is pretty much what I was trying to get to with the connection stuff...I also completely agree with your other arguments :-)

Scott Galloway

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 8:45 AM

Excellent post. We had a major project at my last employer that had a DBA writing (or at least approving) the stored procs for rather routine CRUD, a junior developer writing wrapper classes around all of those stored procs, and then the application developers only had to worry about consuming those data libraries. Looked great on paper, since this was an n-tier architecture with lots of separation, and we all know that's supposed to make our lives and maintenance easier. The problem was that it did not make anything easier, since nearly every change in the database required at least 2 people, if not 3. These changes also had to be coordinated very well, since anyone done out of sync, or too late, would break the build, and this did indeed happen. I think our DBA felt very threatened when I talked about O/R mappers, but I honestly think these tools would actually finally have given him the freedom to worry about the database design and performance optimization, instead of writing routine CRUD procs. The junior developer would also be freed up to actually become a real application developer, instead of just being another wasted body. So, down with stored procedures -- long live SQL!

Paul Wilson

# Does an OR Mapper need to use dynamic sql?@ Tuesday, November 18, 2003 8:46 AM

TrackBack

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 8:59 AM

@phil: 'It is also due to the reduction of round tripping...'

This is not the case, you can use a whole batch of T-SQL commands in a single call resulting in a single network roundtrip, so it is the same number of round trips as if you would call a SPROC: 1!

Marc Hoeppner

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 9:21 AM

Marc: Good call on saving the round tripping with multi-statement SQL.

But I would hate to run into this type of code personally. I mean, you are basically writing a stored procedure at that point and hard coding it into your app. Most of my development is in VB, but I would have to switch to C# just to be able to get away with not having to use the dreaded _ and & to build the string together to get that sucker to run, and be maintainable. Once again, my personal preference.

Now as Paul brings up, your opinion of stored procedures really depends on your environment too. I personally would I simply set fire to the building with the three person tag team on the CRUD development.

It might just be the relatively small nature of the projects I've been working on (15-30 tables), but I've managed to escape writing simple CRUD sprocs. Most of my sprocs look something like "AddOrder", "GetOrdersByCustomerID" and things like that. I have been given the power of writing my own sprocs, if I had to go to a DBA to get that done, well, if you've seen kill bill you know the type of violence that would ensue.

The only time I seem to not be using stored procedures is when I'm working with data adapters and datasets. I see no real reason to use stored procedures for the reasons outlined here by everyone else. But in my connected environment land, I'd rather use stored procedures instead of using the work arounds that people have presented here.

Phil Scott

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 9:25 AM

Paul: exactly my point.

Phil: giving developers access to stored procs is not helping you a lot. You have to insert/update data anyway, there ARE sp's in the API which do that. So the argument is pretty moot if you ask me, but nevertheless, if you are REQUIRED to do so (even when the arguments for those requirements are not that great) you don't have a choice. If you DO have a choice: think twice.

Frans Bouma

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 9:30 AM

@Phil Scott:
::But I would hate to run into this type of
::code personally. I mean, you are basically
::writing a stored procedure at that point and
::hard coding it into your app

Totally wrong.

If you do it right, you write a SQL generator that is able to take advantage of batching, as I do right now with the EntityBroker. Nothing else.

My programs will use batching, but I will never "code a SP into my app". Never.

Thomas Tomiczek

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 9:31 AM

@Phil: Is it really that different? - You are going to 'harcode' it anyway: You build your SQL either with Query Analyzer or another tool. When you are done, you type in your SQL code into an editor (=hardcode it) and run the program to get the results. Now, in one case your editor may be the SQL Enterprise Manager, creating a SPROC. In the other case this may be VS.NET and you enter the T-SQL in a VB.NET or C# script. In any case, you effectively 'hardcoded' it!

And I agree the @ really helps :)

Marc Hoeppner

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 9:31 AM

Simply wrong. There are things a Stored Procedure can do that would take many round trips for Dynamic SQL.

If you think sending a huge multi-statement query request across the wire is more efficient that a simple SP call - you haven't played with a slow connection much.

I don't know how many times I have found a bug in a Stored Proc, fixed it and did not have to redistribute client code.

Code reuse between applications is greatly enhanced. A list of active employees is made available without having to give rights to the Personnel DB to every Tom, Dick & Harry.

Mike Potter

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 9:37 AM

Marc:

How is:
myCustomer.Save();

or
DaoAdapter dao = new DaoAdapter();
dao.Save(myCustomer);

hardcoding sql?
It's not. You require logic to distinguish insert from update, when update, what to update, etc. Nothing is hardcoded. That's the point.

Filtering on entities in the database is dynamic: you formulate your filter right there where you need it. This for example requires 2 arguments. If you want that in a stored procedure, you would add 2 parameters. Another query in your app does the same filter, but with 3 arguments. You have to alter the stored proc or create a new one. Adding a new parameter will break the 2 parameter call. So you have to alter THAT CODE as well. Which is weird, because with the dynamic query you wouldn't have to alter that query.

Frans Bouma

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 9:52 AM

Right-on! I've been on the stored proc bandwagon long enough.

Eliminating stored procs is not silly. I'll take a nice and tight database layer over procs any day.

SteveL

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 9:56 AM

@Frans:

I was just replying to Phil as he said he feels that using SQL inside code is 'hardcoding' it (if I understood him correctly). So I was just comparing SPROCs to 'hardcoded' SQL inside a SqlCommand, for example :)

Now, if you enter the world of dynamic SQL for CRUD operations you are absolutely right. If you don't use such a ORM tool, you _will_ have to hardcode your CRUD SQL somewhere, either in a SPROC or inside a call to, say, SqlCommand()!!

Marc Hoeppner

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 10:01 AM

@Mike:

>Simply wrong. There are things a Stored Procedure can do that would take many round trips for Dynamic SQL.

Care to share an example?

>If you think sending a huge multi-statement query request across the wire is more efficient that a simple SP call...

Nobody says that. The point is that a multi-statement query will be _as fast_ as a simple SP call. Not faster, not slower :)

If you work across a 56k modem to your DB, you are indeed working on a different set of problems. In this case, I agree with you that even the few extra bytes like a few hundred bytes of T-SQL code may add up.

Marc Hoeppner

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 10:02 AM

Marc: hardcoding crud statements is not something you have to do. Using a dataset for example, you can create your insert/update statements on the fly. The data you have to use in an insert/update statement lives somewhere, you can use that to create the statement. Using a generic block of code you can reuse.

Frans Bouma

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 10:11 AM

So, when is your Database Object released? :P

Nielsz

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 10:13 AM

Marc, you understood me correctly. Just poor wording on my part. At 10am my brain has flipped it's "write coherent" bit on.

Of course it isn't that different, it is just a matter of preference for me. I'd much rather have that code as stored procedure on the server than on the client, that's all. And as Mike said, depending on the type of connection sending a 2000 byte sql statement vs a 20 byte stored procedure name might add up depending on the architecture and the clients needs.

O/R tools, and dynamic sql generators are always great tools to have, and if I have access to an easy to use and powerful one I'd take that any day of the week over writing sprocs by hand. But not everyone has the resources or even the need to have such a tool on hand.

I can't see how anyone in this case has been totally wrong or how one way of doing things would be the "right way" over another. Each method is going to have it's pros and cons. I think if you are using an O/R tool or the DataAdapters you aren't going to be seeing any benefits from using stored procedures. But for those who are (god forbid) using DataReaders and sending SqlCommands directly, I feel I'd rather use sprocs for that.

Phil Scott

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 10:14 AM

@Frans: Using CommandBuilder?? - This is definitely _not_ a good idea. It may work for simple tables, but as soon as you start to have more complex scenarios, it stops working. 'Complex' scenarios start with using JOINs and multiple PKs etc.

Marc Hoeppner

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 10:15 AM

At my company, we have 3 software products that work against SQL Server, Oracle, and DB2 with the flip of a switch. We have built it using dynamic SQL within our code and all 3 have been around for years. These are big apps and, in the end, they are very maintainable.

Imagine trying to sell your product to a company's IT group and saying that it relies on stored procedures. Guess what...the DBA is going to shoot it down because he knows that as new releases come out, it is going to be a huge pain in the ass for them to update and maintain changes to the SP's. Now tell them that they don't have to do anything. All the SQL is managed in the code itself. Well, you know their reaction.

Maybe an in-house application where I know the back-end will always be SQL Server or Oracle or whatever, I would use SP's and love them. That's just not the case for a product-based application. At least in my experience it isn't.

JW

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 10:19 AM

Marc: no not using commandbuilder:) Using a component you write yourself (or buy). You feed it the objects it should generate DML for and it generates that DML, including parameters. Execute that and you're set. Cache the result on the client if you will so you don't have to regenerate the statement. A dataset has the schema inside itself needed to generate the code you need. (I use the 'dataset' example, since Scott accused me of writing a blog to sell my O/R mapper LLBLGen Pro which is not the case at all :) ).

Frans Bouma

# Dynamisk SQL eller SP?@ Tuesday, November 18, 2003 10:20 AM

I det seneste d

TrackBack

# Ever heard of role-based security?@ Tuesday, November 18, 2003 10:20 AM

TrackBack

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 10:39 AM

As far as Paul's comment about breaking client code by making changes to the stored procedures: This is no different than changing the rows a view returns as far as breaking things, and as for parameter changes, the best way to handle this is to add a parameter with a default value that works for everyplace the SP is called except the place that needs the new parameter. A good DBA does not break client code. A bad DBA will mess up any architecture.

Douglas Reilly

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 10:45 AM

Pre-compilation of a query plan does not exist, but that is not to say that plan re-use is not a performance benefit. 2nd and future executions of a stored proc will run faster (how much faster depends on your hardware).

A stored proc which gets the last name of a customer by customerid should outperform a straight execution of "select lastname from customer where customerid = 12345". But an external component that dynamically builds *AND PARAMETERIZES* a query (basically runs it through sp_executesql properly) should perform on par with the stored proc. I think that's a point people are missing when arguing against dynamic SQL.

Over-the-network performance benefits of passing "sp_Crap" instead of "sp_executesql 'SELECT crap'" are usually negligible these days with the fat network pipes.

Mikey

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 10:45 AM

@Frans

Yepp, like I said, I was not trying to argue against the advantages of using something like ObjectSpaces ;) - But if you don't have that at hand, you are likely to hardcode your SQL code either into a SPROC or inside C# (or whatever) code. JW makes a good point though, that such a tool should be able to support both auto-generated SQL code as well as existing SPROCs as it simply is a requirement for some companies. Still, it doesn't change the general argument that we have here about the technical pros/cons of SPROCs. The business side is still something else to consider on top. On the other side, if you develop a product and deploy your own DB, I definitely want to make sure that the DBA _has no chance in hell_ to 'tweak'/'enhance'/ruin our SQL code ;)

Marc Hoeppner

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 11:37 AM

I think you need to address the comments about Round Trips. The biggest aspect of stored procs is that they live close to the data. So, if you are doing simple processing - sure. However, if you are doing complex processing, requiring multiphase transactions - interim result sets (changing logic and flow based on interim result sets) - I don't see why stored procs wouldn't be used. When you need to pass everything out of SQL - you are working on layer (the network layer) that is literally 1000's of times slower then memory. This isn't good. I don't know about apps that you write - but apps that I write tend to have very complex rule implementations - and data manipulation isn't confined to simple SQL statements. They may require many many many nexted transactions - sub-queries, multi-stage processing, etc.

I do agree, however, that sp's are misused for the wrong reasons with regard to performance, security, etc. But, in the real world (architecturally) they are a fact of life. If they didn't represent some level of goodness, why has Oracle been promiting Java in the db for years. Why are we so excited about having managed code live in Yukon? - its all about round trips and reducing network traffic as much as we can. Chatty apps are bad apps.

Joel

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 11:40 AM

::If they didn't represent some level of
::goodness, why has Oracle been promiting Java
::in the db for years. Why are we so excited

Because Oracle was always the worst of all databases, from a SQL point of view. Their query analyzer literally sucked - all performance out of the server by being too stupid to see the most obvious things.

So, Java in the database was the way they "solved" this.

::about having managed code live in Yukon? -

Are we? Really? I am not.

::its all about round trips and reducing
::network traffic as much as we can. Chatty
::apps are bad apps.

Not necessarily. You can neutralize - pretty often - most of the impact with a good application server. Not always, though - and then you start hitting the last percentage of gains.

Again on the "Chatty apps are bad apps".

Why d you think a company like Persistence (http://www.persistence.com) has proimoted to be times faster than a SQL database for years? Because it is not always true what you say.

Thomas Tomiczek

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 11:43 AM

Some stored procedures are pretty complex and big in size. Having them as sql queries being resent by hundreds of clients is a network bottleneck. They also eliminate round trips. You can encapsulate all your SQLs in one call.

Some SQL statements span different databases across different servers (linked servers). This means these clients need to to have access to these servers.

How come your first LLBLGen used SPs only?

Abdu

Abdu

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 11:48 AM

"How come your first LLBLGen used SPs only?"
I wrote that tool in a time when I was fully convinced stored procedures were much better, and way faster than dynamic sql. After I've hit the wall and learned that this is not the case, I gave up on stored procedures. That's why LLBLGen Pro generates all sql on the fly. It still can call sp's if you want to, but not for entity usage.

Frans Bouma

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 12:13 PM

@Joel

I don't think anyone is asking to drop SPROCs off the feature list. I totally agree that there are good reasons/cases when you should use SPROCs. The general argument started with Rob saying that you should use SPROCs always and everywhere. That's where many people including myself disagree. But that doens't mean that SPROCs are useless, quite the opposite.

Yukon solves many problems I/we have with SPROCs, for example versioning and multi-developer scenarios, let alone the whole deployment stuff. Still, I think that tools like ObjectSpaces, EntityBroker or the beloved LLBLGen have their merits even in the Yukon timeframe. Using parameterized queries still will keep the action where it should be (on the DB server using SQL) and the few extra bytes on the line surely don't make a real difference for most apps, at least IMHO.

Marc Hoeppner

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 12:39 PM

> you should use SPROCs always and everywhere

Please don't misquote me. I did not say this and I clarified it further here:
http://weblogs.asp.net/rhoward/posts/38298.aspx

The main point that I am making is that you should take advantage of the platform you are running on. If there are platform specific features that you can use to better your application than you should take advantage of those features.

Rob Howard

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 1:07 PM

@Rob

From your original post:
>At just about every talk I give I always try to make several consistent statements. One of which is: ‘Whenever possible use stored procedures to access your data’.

I think this statement is much to general in nature, so I don't feel I misquoted you saying 'with Rob saying that you should use SPROCs always and everywhere'.

Marc Hoeppner

# Stored Procedures vs. Dynamic SQL@ Tuesday, November 18, 2003 1:19 PM

TrackBack

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 1:21 PM

::>At just about every talk I give I always
::try to make several consistent statements.
::One of which is: ‘Whenever possible use
::stored procedures to access your data’.
::
::I think this statement is much to general in
::nature, so I don't feel I misquoted you
::saying 'with Rob saying that you should use
::SPROCs always and everywhere'.

I would say the original statement is cromoinally wrong.

See, "Whenever possible" means "also when it makes no sense". Even when you end up with a simple "select * from table where id = ?" in the SP, this would mean "use a SP, just because it is possible".

Basically, the statement means: use sp's for everything unless you use MS Access or another database which does not know SP's.

The quote from Frans (sorry, Rob) was right.

Thomas Tomiczek

# Stored Procedures vs. Dynamic SQL@ Tuesday, November 18, 2003 1:43 PM

TrackBack

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 2:19 PM

Use a stored procedure if the roundtrip savings are worth the decrease of maintainability, flexibility and compatibility. We tend to call this "the zone". "The zone" where business logic is factored tighter and tighter to your db scheme. Besides the people who wrote OR mapping tools probably compared execution plans (SQL server) and must have noticed dynamic SQL is way faster due to SQL server's crappy stored proc optimisation when precompiling.

Paul Gielens

# re: Stored procedures are bad, m'kay?@ Tuesday, November 18, 2003 3:11 PM

I Think that after eight years of keeping stored procedures you become tired of them and you'd rather prefer your comfort than a well designed application.

Rob's got a point on it

Harley Jácome

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 4:39 AM

I'm surprised that noone has mentioned the merits of using SProcs in a secure environment yet. For those DB's where complete access security defines the method of data access, SProcs are really the only way to go.

Say for example I have a DB using Windows Auth to restrict who can view what data. The DB is being accessed by three or four different apps. Now on that DB I have something like 100 tables, which I do NOT want the casual browser (using Query Analyser) to be able to view. I therefore need to lock down access to all tables. Access MUST then be made through SProcs. I know - I could just allow access to the tables through defined logins. But what if I need two different roles (Staff vs. Managers - defined by NT Domain groups) to be able to retrieve different sets of data from the same tables? And what if the access levels that particular users have are to changed? For example - a Manager can only view payslips for those employees that work directly for him instead of the whole department? That would require the code of three or four applications to be changed. I'd rather change one set of SProcs...

The point I'm trying to make is that if you are developing an application in which any kind of sensitive/personal data is involved, or where Role-based access to data is necessary, or you are required to ensure that this data is kept secure - Dynamic SQL will not be your best friend. In these instances only SProcs will help. In fact I'd go to say that if you are designing/developing with security in mind from the start, then you'd be daft not to use the in-built security that SProcs offer you.

Mike

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 4:49 AM

Mike: the time it takes to create all those stored procedures for each role can also be used to create the views you want. The advantage of that is that you can use views in queries (FROM clauses) you can't do that with sprocs.

People think that in a high-secure environment, stored procedures will be much more secure AND it will take way less effort. This is not true: for each byte you want to return as a select result, you have to write a procedure. That code can also be used to write a view.

Frans Bouma

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 5:15 AM

What about writing your business logic in a stored procedure?

Frederik Gheysels

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 5:59 AM

What about user defined function which return tables (sql 2000) (view with parametars).
Should we use it Frans,
or we should buy your LLBLGEN Pro.

Crazy Chess Player

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 6:02 AM

Depends on what you want to do with the user defined functions. afaik, you can't call them from outside the db.

Frans Bouma

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 6:03 AM

::What about writing your business logic in a
::stored procedure?

Perfectly valid approach.

Just dont tell people then that you follow object oriented programming - you are simply not.

Thomas Tomiczek

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 6:21 AM

> afaik, you can't call them from outside the db.
I don't think so.
http://msdn.microsoft.com/msdnmag/issues/03/11/datapoints/

Crazy Chess Player

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 6:34 AM

Chess Player: I meant calling them as a stored proc directly using a Command object, afaik, you can't do that, it always requires a T-SQL statement which references the function (calling it). Of course you can call them embedded in an SQL statement, like the article shows. (the article is not that correct though, it says stored procedures are compiled and views aren't. Well, the code of a view is placed at the spot where the view is referenced. This means that a stored proc using a view contains in its execution plan the compiled code of the view. At least that's what BOL tells me.)

Frans Bouma

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 6:34 AM

>Perfectly valid approach.

>Just dont tell people then that you follow object oriented programming - you are simply not.

Sometimes, you have to make trade-offs between perfectly valid OO and performance.

Frederik Gheysels

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 6:43 AM

::Sometimes, you have to make trade-offs
::between perfectly valid OO and performance.

Yes, but these are fwwer than you think.

Becaue the one thing totally ignored so far is that a good OO DAL would introduce a nice little cachin opportiunity, too :-)

AND: the performance tradeoff is only a valid argument when necessary. Otherwise you just blow out the maintainiability of the app for a performance gain you dont use. BAD decision.

But sometimes, for certain simple procedures, it really is good to put them into an SP.

Thomas Tomiczek

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 6:55 AM

:Frans Bouma
:Posted @ 11/18/2003 2:20 PM
:Wallym: the dramatic performance boost is not
:there, because the stored procs are threated
:as queries which arrive at the sql engine:
:they are compiled at runtime.

Frans, I respectfully disagree. My experience has been that sprocs do provide a dramatic performance increase. The issue is when is this performance boost needed vs. ease of programming.

Thomas Tomiczek, you sound like a ranting child. I stand by my statements and the standards that I use.

Wally

Wallym

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 7:01 AM

"Sometimes, you have to make trade-offs between perfectly valid OO and performance."
Placing BL in de stored procs has nothing to do with OO or not, it has everything to do with separation of functional tiers. Moving BL into the procs is colliding everything together. This was done in the old days too, where queries were executed in a button handler. Worked faster, but was unmaintainable.

Frans Bouma

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 7:04 AM

"My experience has been that sprocs do provide a dramatic performance increase. The issue is when is this performance boost needed vs. ease of programming. "
While I most of the time agree with your opinions, I have to say this opinion of yours is just what it is: your opinion, not based on fact, just on personal experience. When I look at the theory behind the sql compiler in sqlserver, I can't conclude anything other than that a dyn. parametrized query and a stored proc run as fast, because both will use a cached execution plan. (yes, dyn. query has to be compiled first, so does the proc, which also will have to be recompiled if you're not careful (and the more code you add to make them flexible the more risk you take to cause a recompile of a stored proc on every occasion)

Frans Bouma

# Stored Procs or Dymanic SQL@ Wednesday, November 19, 2003 7:06 AM

So yesterday a debate surfaced that seemed to have the entire online programming community all worked up. Rob Howard, Microsoft ASP.NET Program Manager, posted to his blog about using stored procedures in SQL server. Many comments both for and against Rob's arguments in his post ensued. Things got a little heated when Frans Bouma stepped into the debate. Frans took his ideas to his own blog, and then you see the entire blogging community step in (via their own respective blogs) to add their own take on things. What a day.

TrackBack

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 7:41 AM

::Thomas Tomiczek, you sound like a ranting
::child. I stand by my statements and the
::standards that I use.

This is ok. It does not make your stnadards any moe meningfull, though. And this is what you should care about more, you know. Especially given the number of arguments you give in here.

@Frans:
::yes, dyn. query has to be compiled first, so
::does the proc, which also will have to be
::recompiled if you're not careful (and the
::more code you add to make them flexible the
::more risk you take to cause a recompile of a
::stored proc on every occasion

Even worse. You end up ith having a "with recompile" option on the SP pretty fast. Because all these neat tricks for handling variable numbers of parameters end up killing your performance. The cached plan will be the one selected by the first set of parameters discovered. All other requests goind in will reuse the compiled execution plan, whether this makes sense or not. This can only be avoided when you dont work with "dynamic numbers of parameters".

What I mean are sp's like this:

getUserData (fitlerName, filterCountry)

where both could be null. Depending on the selection you end up with either one or two or zero where conditions.

In a SP you can:
* Make a series of IF statements and HAVE threee statements. Efficient, but ugly as hell.

* Make one statement that uses conditions. Way less code and pretty nice - but basically the cached execution plan is determined by the first set of parameters.

Rsult: With option Recompile, and there you say then "whow, I did reuse plans", becuase you basically had to kill your performance gains.

Alternatives: three different SP's - not better than avariant one, and ugly as hell.

With dynamic SQL the SQL generator can handle this on the client side.

The main problem ith SP's here is that I know a lot of occasions where this dynamic thing turns around and bites you faster than you can say "I was an idiot programming this", and this is basically whenever you show a powerfull query form to the user. One where the user may be able to select multiple conditions. One like, btw, the "Advanced Find" in Outlook (on the Advanced tab, btw.). I would basically say it is nearly impossible to code someting like this in an efficient set of SP's on the database - the most efficient way to do this IS dynamic SQL, as the query is dynamic.

So, as a summary: SP's bite you when you go dynamic in the application. Now, it is up to you to decide to write applications that empower the user big enough that you realize you just got killed by sp's. Naturlly we all do this, right? We all make configurable software, using command patterns etc. Right?

Thomas Tomiczek

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 7:58 AM

>>yes, dyn. query has to be compiled first, so does the proc

What's the use of the 'WITH RECOMPILE' clause then the 'CREATE PROCEDURE' in Sql Server ?
I also thought that you could recompile a SP in Sql Server explicitly, so why would the SP be recompiled every time it's called?

/me needs to do some investigation on that subject.

Frederik Gheysels

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 8:05 AM

Frederik: WITH RECOMPILE means the proc will be recompiled no matter what on each access: (From BOL) "Creating a stored procedure that specifies the WITH RECOMPILE option in its definition indicates that SQL Server does not cache a plan for this stored procedure; the stored procedure is recompiled each time it is executed"

It can be better to signal sqlserver to not bother to cache the plan and to lookup the cached plan only to find out it has to recompile the procedure anyway. There are situations where a stored procedure will be recompiled anyway because of different codeblocks being executed, temp table usage in IF statements etc.

Frans Bouma

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 8:16 AM

You may call this "Product Pimping" (which it isn't, I can only point you to relevant technology based on the content of your posts when such exists), but if you want to back up your observations with empirical data (there are a number of critical variables that affect the claims that you are making either way). Stored Procedures and Dynamic SQL aren't mutually exclusive, they can actually be combined in appropriate situations. simply obtain the Open Source ODBC Benchmark Utility for ODBC or JDBC that we provide from http://www.openlinksw.com/download that pretty much covers all the relevant scenarios. If ODBC or JDBC are in the picture and escape syntax is understood and appreciated, then post utilization of the ODBC and JDBC bench tools you will see that Stored Procedures are a network optimization (reducing RPC count) primarily.

Kingsley Idehen

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 8:23 AM

What's so interesting of benchmarking something over ODBC? What's reality for ODBC doesn't have to be reality for native ADO.NET providers. Example: ADO over ODBC doesn't call sp_executeSQL per se when you execute a dynamic statement, SqlServer's client for ADO.NET does.

Frans Bouma

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 8:25 AM

Frans ,
You are right about calling
but you can wrap it in sp
and call sp :).
Another usefull article.
http://www.fawcette.com/vsm/2003_09/magazine/columns/databasedesign/default_pf.aspx

What is important for me :
1.don't use concat for making sql on client
2.there is not perf diff in using SP
and sql with params for SQL 7 >>
(you can see that if you compare Pet Shop .NET
last one is done without sql proc )
3.May benfit from OR maping tools is developer productivity ?
(Prove it! for example you can make
Database Layer
Pet Shop .NET with your tool)
and compare number of lines and developer effort.Like M$ has done against Java$.
4.Visual studio .Net is great tool not only
for .NET language but also for working with
MS SQL SP.
5.In my oppinion you must know database
(PL-SQL ,Transact SQL) if you are making
database aplication against Oracle or SQL
6.I did not use OR maping because
I know SQL very well, but if it can save me some time why not?

Crazy Chess Player

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 8:38 AM

ChessPlayer:
"1.don't use concat for making sql on client"
Of course not :) I use string builder objects and in some occasions String.Format() (which is also very efficient). I also use AppendFormat() to add as much text as possible in one go.

"3.May benfit from OR maping tools is developer productivity ?
(Prove it! for example you can make
Database Layer Pet Shop .NET with your tool)
and compare number of lines and developer effort.Like M$ has done against Java$."
It took me some time to get the correct petshop database model :) (MS' one is not that great). It's the plan do write teh petshop example, I hope to finish it soon.
"4.Visual studio .Net is great tool not only
for .NET language but also for working with
MS SQL SP."
You gotta be kidding :) Did you ever wrote a SP in vs.net and had a typo? :) "Error", err... yes, but where? :D

"5.In my oppinion you must know database
(PL-SQL ,Transact SQL) if you are making
database aplication against Oracle or SQL"
No. With an O/R mapper this is totally abstracted away. The only think that is very handy to have is a relation graph, thus which entities are related to which entities. But you can print that using enterprise manager.

Frans Bouma

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 8:58 AM

"4.Visual studio .Net is great tool not only
for .NET language but also for working with
MS SQL SP."
I even debug it in Visual studio .Net
5. I think your answer is main reason why
lot of database app fail.
one more link from oracle database guru
author of
"Expert One on One Oracle "
by Thomas Kyte (Author)
http://www.databasejournal.com/features/oracle/article.php/10893_1403591_2
I will quote him
"If you do not understand what your particular database does or how it does it, your application will fail. If you assume that because your application ran fine on SQL Server, it will necessarily run fine on Oracle then, again, your application is likely to fail."

Crazy Chess Player

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 9:05 AM

That quote is based on the assumption Oracle supports as much SQL-92 standard statements as SqlServer does (and vice versa). Both have proprietry statements to do stuff (8i can't join ANSI style, 8i/9i don't have FROM clauses in delete/update etc. (delete has 1 from, not 2)...). This obviously will make an app fail.

However I generate SQL on the fly using components that are specialized to do so per database. Thus 1 for sqlserver, one for oracle etc. The code targeting these objects is the SAME (which is the code a developer would write), the sql generated at runtime differs, because the engine used to generate it is different for oracle than for sqlserver. Using the same engine is indeed not handy. :)

Frans Bouma

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 9:25 AM

Sorry but I agree with him.
One more quote:
"These may seem like surprisingly obvious statements, but in my experience, I have found that too many people approach the database as if it were a 'black box' — something that they don't need to know about. Maybe they have a SQL generator that will save them from the hardship of having to learn SQL. Maybe they figure they will just use it like a flat file and do 'keyed reads'. Whatever they figure, I can tell you that thinking along these lines is most certainly misguided; you simply cannot get away with not understanding the database. This chapter will discuss why you need to know about the database, specifically why you need to understand:"

Remerber EJB and all that object mapping staff
(Top Link)
for java and database.
Good Luck!!
But I don't belive in that:
"No. With an O/R mapper this is totally abstracted away. The only think that is very handy to have is a relation graph, thus which entities are related to which entities. But you can print that using enterprise manager."

Crazy Chess Player

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 9:34 AM

You don't believe me? That's fine. I don't see the point in learning SQL when you are not using it at all. The definitions (very important) of what people want are the same for every database. the SQL generated is different.

It's like claiming knowledge of MSIL is a must have to be able to write C# succesfully, or to understand how NTFS works to be able to use the I/O subsystem via System.IO.

Frans Bouma

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 10:07 AM

Don't be angry ;).
Let say it this way: Set of SQL generated by your tool is probably subset of what I already generated manually in my stored procedures or sql statements with parameters.
I bet that your tool would not solve some practical problem that I solved with sql.
If the developer uses your tool and does not know SQL in my opinion he ( or she) will sooner or later has unsolvable problem that require SQL.
In my opinion everything you can do in IL you can do in C#, which is not true for OR mapping tools.
C# = IL
SQL > LLBLGen Pro



Crazy Chess Player

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 10:14 AM

Well, for DML, not really. For special selects, I agree, you can never mimic RDBMS native functions well enough, however dyn sql engines can get very close. It depends on what you need and besides aggregates, you don't need a lot of specific SQL statements a lot in a *LOT* of situations. for the rare situation that you do, you can fall back on creating a view or indeed a stored proc, but these situations are rare.

Frans Bouma

# re: Stored procedures are bad, m'kay?@ Wednesday, November 19, 2003 11:00 AM

Be sure and read my replies after researching with the SQL team and several outside SQL exeperts:
http://weblogs.asp.net/rhoward/posts/38446.aspx

Rob Howard

# re: Stored procedures are bad, m'kay?@ Thursday, November 20, 2003 6:24 AM

Being quite fond of stored procedures myself, it's been a real treat to read this blog-entry and the following discussion to get some input.

I don't believe there is only one correct way to do things, nothing is just black or white. Different problems require different solutions, and only the specific scenario decides which is better: dynamic sql or stored procedures or perhaps a mix.

That said, I'll provide you (all) with a little more input to shoot at :-)

Firstly, why hasn't anybody produced comparative benchmarks? How can you argue that dynamic sql should be just as fast as stored procedures with no data to back it up - or the other way around for that matter. Books online is a great source for information, but is it absolute truth? (I won't either, btw)

Regarding the use for sprocs, it's true that if you don't write your stored procedures correctly, you may as well use dynamic sql statements. But I think this is because of a common misconception. Procedures are not a place to put business logic and as such there should be no need for conditionals, behavioural bits and the like, and therefore no need for recompilation. If you can't manage without them, your design must be wrong somehow. (Yes, I'm sure there are tons of counter-examples, but in general...)

As for O/R-mappers, my experience is that they're not very good at handling complex relationships, and if you have to write the code that generate the SQL yourself, you may as well put the statements as procedures in the database and write a wrapper (or use someone else's - ie. Microsoft.ApplicationBlocks.Data for .net). Oh, and you can use dynamic discovery of sp-parameters the same way you dynamically discover changes to a table.

In my opinion, the best argument against stored procedures is the "maintainability"-issue. 4+ sp pr. table/object and corresponding wrappers can get hairy to maintain and is a huge source of errors. However, the strength of the approach is that you can test the persistence part of the application systematically - this is a little tricky with generated code. If you find an error, replacement is a matter of rewriting (and testing!) a few lines of code. I guess testability and maintainability have some sort of trade-off relationship, that need to be taken into account when planning the project.

There, my 2 cents
Mikkel

Mikkel R

# Now this really bugs me...@ Saturday, November 22, 2003 1:16 AM

TrackBack

# Frans - u r so wrong@ Saturday, November 22, 2003 3:45 AM

sprocs are the way to go.

1. It is a packaging issue - I do not want my
sql code to be buried in all C# source files
all over.

2. I can test them and sql optimize them as batches.

3. Read up on the 'compilation' stuff - you have it wrong.

Plug - My tool (www.dbcodegen.com ) generates
generates C# bindings for sprocs as well.

Ricky

Ricky Datta

# re: Stored procedures are bad, m'kay?@ Saturday, November 22, 2003 7:25 AM

::1. It is a packaging issue - I do not want
::my sql code to be buried in all C# source
::files all over.

With all respect: if you are too stupid tp keep your SQL - even if you use handcoded dynamic SQL - in one place, you should not program but sell fries at burger king. SP's or not have NOTHING to do about keeping SQL in one place. Even SP's need to be called, and when you scatter these calls all over your code, your architecture is as rotten as the sample you gave.

You can ALSWAYS centralize this. SP or not.

::2. I can test them and sql optimize them as
::batches.

Yes, and you can do so all over the place over and over and over and over again, for multiple databases if you want to support more than SQL Server.

Sometimes this is needed. Normally it is the typr of timewaster that makes you loose your job as your company is not competitive enough.

the vast majority of db operations are simple and extremely boring. Linear CRUD operations. The majority of the rest are complex queries. In both cases, SP's dont gain too much.

Unless you start moving business logic INTO the database. THEN you can gain tremendously in some scenarios, but this is an architecutral decision. Just say goodbye to OO.

::In my opinion, the best argument against
::stored procedures is the "maintainability"-
::issue. 4+ sp pr. table/object and
::corresponding wrappers can get hairy to
::maintain and is a huge source of errors.

Absolutly.

::However, the strength of the approach is
::that you can test the persistence part of
::the application systematically - this is a
::little tricky with generated code.

No, it is simply not necessary in generated code. The code generator will not emit buggy code. Period. A good one will even validate that the generated code is working (I work on something like this for our EntityBroker O/R mapper right now - it will go through the database and make sureit's metadata is correct).

So, there simply is way less need to validate anything.

Naturally this is only the case when you get this layer automated, not when you belong to the vast amount of people considering it smart to handlcode the same reetitive routine over and over and over again.

Thomas Tomiczek

# re: Stored procedures are bad, m'kay?@ Saturday, November 22, 2003 11:50 AM

The too-many-cooks argument against sprocs was valid at one time, but code generation now negates it for most cases.

I use CodeSmith to generate sprocs and DAL classes against tables and it not only makes the job cake, it makes coding against the tables (via the classes) trivial. I shaved at least a week worth of manual code on my last project this way. It took all of two minutes to adjust the templates on this page to suit my needs (to use the connection defined in web.config): http://www.ericjsmith.net/codesmith/forum/?f=9&m=402

The DBA needs to change the structure? Regenerate the sprocs and code, recompile the classes in the DAL namespace. Done. The only code that needs to be touched is code that needs to change anyway. But now all my DAL interfaces are consistent, easy to work with, and provide more functionality than if I had to hand-code each.

Code generation against individual tables means that I use additional queries to translate ID codes into English onscreen (or to do .resx lookups for other languages) -- usually these are the same datasets used for the dropdown lists themselves. And these can all be cached. So I get the advantage of both fewer and leaner queries hitting SQL Server for both my dynamic and static data. The translation happens at the UI layer where it belongs.

I still generate a few specialized relational queries on the fly for certain reports. There will always be exceptions, they can't be avoided. But this approach saves me time in all the usual cases, cutting the time I spend writing repetitive code down to nearly nil.

As for performance, sprocs are faster. I've done time trials. Have you?

Take care,
Eli.

Eli Robillard

# re: Stored procedures are bad, m'kay?@ Saturday, November 22, 2003 12:30 PM

"3. Read up on the 'compilation' stuff - you have it wrong."
Which part of "Quote" do you not understand? I quoted the part from the BOL. If you think that text is wrong, BOL is wrong, not me.

"As for performance, sprocs are faster. I've done time trials. Have you? "
Yes I have, see the links at the top. SProcs are slower in fact in my tests.

However 'in my tests, ABC is faster' is bogus to me when there is no explanation given. BOL tells me SProcs and dyn. queries are not treated differently. Therefore one should be as fast as the other. You may think sprocs are faster, if you can't give a theoretic explanation that is TRUE, don't bother claiming they're faster.

Code generation for stored procs is ok, but then also maintenance sucks: you end up with a lot of procs and when the schema changes, which one to remove? All of them? None? Trust me, with LLBLGen 1.x, which generates procs and classes way before Eric Smith thought it was a good idea, I've learned this the hard way: a hell of a lot of procs, all nice, but unmaintainable.

Frans Bouma

# Does an OR Mapper need to use dynamic sql? @ Sunday, November 23, 2003 8:20 PM