views:

1682

answers:

18

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.

+2  A: 

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

GlitterMonkey
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
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
"associated performance improvements", Such as?
David B
+35  A: 

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.

Will
+1 for great analogy
Andrew Hare
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
Sorry, isn't it "Microsoft Wrench 2007 Business Edition"?
Mike Robinson
No, they rolled it into Dynamics.
Will
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
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.
Will
Fredrik Johansson
+13  A: 

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
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
This is the primary answer I've received asking this exact question in the past.
discorax
Prefer this approach myself.. .It narrows all database access to a small set of easily managed channels (the stored procs)
Charles Bretana
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
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
Charles Bretana
Opened a new question. http://stackoverflow.com/questions/421553
Matt Brunell
+6  A: 
  1. Stored Procedures and Linq to Sql solve different problems.

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

Justice
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.
j0rd4n
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.
Justice
@J0rd4n: LINQ to SQL _is_ particular to SQL Server. LINQ is not.
Dave Swersky
+2  A: 

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
+1  A: 

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
A: 

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
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
It might be a function, not a sproc
Wayne M
How about this?var foo = from a in db.Products where a.CategoryType == 1 select a;
Echostorm
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
The fact remains that it is completely unnecessary with LINQ.
Echostorm
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
A: 

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
+16  A: 

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

Steven A. Lowe
+7  A: 

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
Amen, brother !
ObiWanKenobi
+2  A: 

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 M
+2  A: 

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
+2  A: 

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
A: 

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.

Karthik Hariharan
+4  A: 

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.

+3  A: 

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
A: 

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.
RoadWarrior
A: 

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 Rinea