13

My understanding of Linq to Sql is it will take my Linq statement and convert it into an equivalent SQL statement.

So

var products = from p in db.Products
               where p.Category.CategoryName == "Beverages"
               select p

Just turns into

Select * from Products where CategoryName = 'Beverages'

If that's the case, I don't see how stored procedures are useful anymore.

cgreeno
  • 31,943
  • 7
  • 66
  • 87

18 Answers18

41

Sprocs are another tool in the box. You might use your fancy automatically-adjusting wrench for 90% of your tasks, but you can't use that shiny thing on stripped nuts. For that a good ol' monkey wrench is your best friend. Unless you break the bolt, in which case you're stuck with assembly.

  • Agreed, sprocs will be around for a long time, but they're sphere of influence will diminish. Only problem with the analogy: if you break the bolt, you're fired! – jcollum Jan 06 '09 at 20:19
  • Sorry, isn't it "Microsoft Wrench 2007 Business Edition"? – Mike Robinson Jan 06 '09 at 20:19
  • No, they rolled it into Dynamics. –  Jan 06 '09 at 20:25
  • 1
    Hmm. It's an interesting analogy, but does it really address the OP? After all, if you can also use your monkey wrench on those other 90%, why bother investing in the fancy auto-adjusting one in the first place? – Steve Morgan Jan 06 '09 at 20:34
  • Because it's fancy, and doesn't require you to get dirt under your nails while twirling the knurl. Also, no SQL needs to be known. –  Jan 06 '09 at 20:54
  • I agree. Linq is great, and will surely become even greater and more important with more SQL-.NET integration. But, today, T-SQL is way more mature, and my advice is to not adopt new technologies to early - or you will end up rewriting your entire system - and just focusing on adopting new tech instead of focusing on business value. Just remember the step from Webservices & Remoting to WCF, or breaking namechanges (ie SQLConnection vs SqlConnection, etc in .NET 1.0 to .NET 1.1). – Fredrik Johansson Jun 08 '10 at 06:55
19

if that's all you ever did in sql, you didn't need sprocs before!

Steven A. Lowe
  • 60,273
  • 18
  • 132
  • 202
14

Security.

I've seen several "security best practice" guidelines which recommend you do all your data access via SP's, and you only grant privileges to execute those SP's.
If a client simply cannot do select or delete on any database tables, the risk may be lower should that client be hacked.

I've never personally worked on a project which worked this way, it always seemed like a giant pain in the backside.

Orion Edwards
  • 121,657
  • 64
  • 239
  • 328
  • 4
    Actually, it's not a pain in the butt at all. Every project I've ever worked on was done this way. – Robert C. Barth Jan 06 '09 at 20:16
  • This is the primary answer I've received asking this exact question in the past. – discorax Jan 06 '09 at 20:40
  • 2
    Prefer this approach myself.. .It narrows all database access to a small set of easily managed channels (the stored procs) – Charles Bretana Jan 06 '09 at 20:50
  • Note: In SQL Server you can grant, revoke, or deny any CRUD operation (select, insert, update, and delete) on a SQL table. I don't see how sprocs provide any additional security. – Matt Brunell Jan 06 '09 at 20:55
  • Matt: because an sproc might do some custom validity checking before executing the delete statement? who knows. The whole approach seems flawed though... you'll most likely have a DeleteUser sproc and a LoadUser, and the hackers will just use those instead of select – Orion Edwards Jan 06 '09 at 22:38
  • @Matt, not security, management. management & control of the access process, who, what where and how all access is implemented... direct Select security on a table doesn't allow the fine grained control that you can implement in a sProc – Charles Bretana Jan 07 '09 at 00:38
13

Ah, the subject of many a debate.

Many would argue these days that technologies such as LINQ-to-SQL generate such good SQL these days that the performance advantages are marginal. Personally, I prefer SQL experts tuning SQL performance, not general coders, so I tend to disagree.

However, my main preference for stored procedures has less to do with performance and more to do with security and configuration management.

Much of my architectural work is on service-oriented solutions and by treating the database as a service, it is significantly aided by the use of stored procedures.

Principally, limiting access to the database through stored procedures creates a well-defined interface, limiting the attack surface area and increasing testability. Allowing applications direct access to the underlying data greatly increases the attack surface area, reducing security, and makes impact analysis extremely difficult.

Steve Morgan
  • 12,978
  • 2
  • 40
  • 49
7
  1. Stored Procedures and Linq to Sql solve different problems.

  2. Linq to Sql is particular to Microsoft SQL Server.

yfeldblum
  • 65,165
  • 12
  • 129
  • 169
  • 1
    Linq to SQL is not particular to SQL Server. There are providers for many other databases. See http://code.google.com/p/dblinq2007/ for an example. – Jordan Parmer Jan 06 '09 at 20:18
  • These providers are "Linq to Oracle", "Linq to PostreSQL", "Linq to XYZ", etc. Linq to SQL means Microsoft's Linq provider, which is compatible with various versions of Microsoft SQL Server. – yfeldblum Jan 06 '09 at 20:24
  • 2
    @J0rd4n: LINQ to SQL _is_ particular to SQL Server. LINQ is not. – Dave Swersky Jan 06 '09 at 20:36
7

I tend to prefer using stored procedures for several reasons:

  1. it makes the security configuration easier (as mentioned by other posters).
  2. It provides a clearly defined interface for DB access (although responsibility for this could be shifted into other areas, such as a DAL written in C#
  3. I find that the Query Optimizer, in Oracle at least, is able to make more intelligent decisions the more information you give it. This really requires testing with both methods though for your specific scenarios though.
  4. Depending on the developers available, you may have some very good SQL coders who will be better at producing efficient queries if they use sprocs.

The downside is that it can be a pain to keep the code that invokes the sprocs in sync with the database if things are evolving rapidly. The points about producing efficient queries could count as premature optimization. At the end of the day, there is no substitute for benchmarking performance under realistic conditions.

user6535
  • 89
  • 2
6

I can think of several good reasons for stored procedures:

  • When working with bigger tables, it can be hard to generate an efficient query using LINQ to SQL.
  • A DBA can analyze and troubleshout stored procedures. But think of what happens when two complicated LINQ operations from different front-ends clash.
  • Stored procedures can enforce data integrity. Deny write access on tables, and allow changes only through stored procedure.
  • Updating stored procedures is as easy as running ALTER PROCEDURE on a server. If a deployment takes months, and a script minutes, you'll be more flexible with stored procedures.

For a small application that's maintained by one person, stored procedures are probably overkill.

Andomar
  • 232,371
  • 49
  • 380
  • 404
  • Good points. I'd also add that stored procedures are good for inserts and for updates when you don't need referential integrity. Also you may (as we do) already have complex stored procedures and functions which work, it doesn't make a lot of sense to rewrite those. (The simple select procedures I generally do rewrite, however). – Stephen Kennedy Sep 05 '11 at 16:17
3

There are significant associated performance improvements on the SQL Server side of things if you use stored procedures in appropriate circumstances.

GlitterMonkey
  • 95
  • 1
  • 3
  • Much less so now than in the past. Sprocs are sort of the assembly language of SQL server... Good to know, powerful, but really only worth doing in very limited circumstances anymore. – Brian Knoblauch Jan 06 '09 at 20:12
  • Yeah, not really. The query processor caches the query plans based on the sql statement and its parameters, so if you make the same/similar calls, on average, it'll be just as fast as a stored proc. There are edge cases where the stored proc might be faster, however. – Robert C. Barth Jan 06 '09 at 20:14
2

Stored procedure support for LINQ to SQL was included partly for compatibility with existing systems. This allows developers to migrate from a sproc-based system to a fully LINQ-based system over time, sproc by sproc, rather than forcing developers to make a rush to convert an entire system all at once.

Dave Swersky
  • 34,502
  • 9
  • 78
  • 118
2

Personally, I don't care for LINQ. I like a separation of the data manipulation stuff and the code stuff. Additionally, the anonymous types that are generated from a LINQ statement cannot be passed-off to other layers of an n-tier application, so either the type needs to be concretely defined, or the LINQ call needs to be made in the UI. Gack!

Additionally, there are the security concerns (whatever user the LINQ code is calling into MS SQL Server under needs to have unfettered access to the data, so if that username/password are compromised, so is the data).

And lastly, LINQ to SQL only works for MS SQL Server (as it comes from MS).

Robert C. Barth
  • 22,687
  • 6
  • 45
  • 52
2

Sprocs have their uses, just like using LINQ does. IMO if an operation is performed multiple times in multiple places then it's a good candidate for "refactoring" into a Stored Proc, as opposed to a LINQ statement that is repeated in different places.

Also, and this is probably blasphemy to a lot of people here, sometimes you should put some logic into the database and then a sproc comes in handy. It's a rare occurrence but sometimes the nature of business rules demands it.

Wayne Molina
  • 19,158
  • 26
  • 98
  • 163
2

Stored Procedures are useful in many cases, but in General if you are using an ORM you should let the ORM generate the SQL for you. Why should we have to maintain at a minimum of four stored procedures (insert update delete and a single select) for each table.

With that said as people pointed out there are security benefits to using stored procedures. You won't have to grant users read/write to the tables, which is a good protection against SQL Injection.

Stored Procedures are also useful when the logic used to retrieve data is fairly complex. You typicaly see this more in Reporting Scenario's and in which case your probally not using Linq2Sql or some other ORM.

In my opinion if your not generating your SQL but essentially hardcoding it within an app tier, then that should be refactored into stored procedures, and yes there are always exceptions to any rules but in general.

One use of a stored procedure in Linq2Sql might be if you have multiple servers, and are linking to them, you could use a stored procedure to expose data from that other server and manipulate it. This would hide the multiple servers from your application.

JoshBerke
  • 66,142
  • 25
  • 126
  • 164
2

Some things can't be done without stored procedures. For instance, at my previous job, there was a stored procedure that return the current value from a row, and incremented it in the same atomic operation such that no two processes every got the same value. I don't remember why this was done instead of using auto-increment, but there was a reason for it.

FryGuy
  • 8,614
  • 3
  • 33
  • 47
1

Reason : Large amounts of data to move from one table to another.

Let's say that once in a while you have to archive items from one table to another or do similar things. With LINQ that would mean to retrieve let's say one million rows from table A into the DBMS client and then insert them into table B.

With a stored procedure things work nice, in sets.

Andrei Rînea
  • 20,288
  • 17
  • 117
  • 166
0

Lots of people have been getting by just fine without them for some time now. If you can do your work securely and efficiently without them, don't feel guilty about going with pure L2S. We're glad to be rid of them @ my shop.

Echostorm
  • 9,678
  • 8
  • 36
  • 50
0

You certainly don't "need" stored procedures. But they can come in handy if your domain model requires a complex aggregate Entity and you don't have the luxury/flexibility to modify your database tables to fit your domain model. In this case using Linq-to-SQL or another ORM might result in a very poorly performing set of database calls to construct your Entity. A stored proc can come to the rescue here.

Of course, I would advocate using a methodology or process like TDD/BDD that provides you the flexibility to modify your database tables as needed without much pain. That's always the easier, more maintainable path in my opinion.

-1

Simple example:

select * from Products where GetCategoryType(CategoryName)=1

GetCategoryType can run really fast, because it runs on the DB server. There's no Linq to SQL substitute for that as far as I know.

Wouter van Nifterick
  • 23,603
  • 7
  • 78
  • 122
  • How would you do that in an sproc? It looks like something that would be achieved with a join? In which case L2SQL can do joins just fine :-) – Orion Edwards Jan 06 '09 at 20:18
  • It might be a function, not a sproc – Wayne Molina Jan 06 '09 at 20:26
  • How about this? var foo = from a in db.Products where a.CategoryType == 1 select a; – Echostorm Jan 06 '09 at 20:28
  • Yes it's a stored function, but that doesn't change the fact that Linq to SQL cannot replace stored routines, be it procedures or functions. Not in functionality, and not it performance. – Wouter van Nifterick Jan 06 '09 at 20:39
  • The fact remains that it is completely unnecessary with LINQ. – Echostorm Jan 06 '09 at 20:49
  • you don't really want to do this, calling to a function in a where clause forces that function to be called for every possible row in the result set. If your products table is BIG, this is going to be a very expensive operation. This is I think an excellent example of why not to use sprocs/functions – Robin Mar 12 '09 at 09:15
-1

I'm coming rather late to this thread. But depending on who you talk to, Linq to SQL is either dead, very dead, or at best a zombie.

In addition, no single tool suits every situation - you need to choose the right tool for the specific job in hand:

  • Stored procs enable you to enforce complex business rules across multiple client applications.
  • Stored procs can give you a great security layer.
  • Stored procs can give you a great abstraction layer.
  • Stored procs can give you better caching in some circumstances.
Community
  • 1
  • 1
HTTP 410
  • 17,300
  • 12
  • 76
  • 127