<p>What are the advantages/disadvantages of keeping SQL in your C# source code or in Stored Procs? I've been discussing this with a friend on an open source project that we're working on (C# ASP.NET Forum). At the moment, most of the database access is done by building the SQL inline in C# and calling to the SQL Server DB. So I'm trying to establish which, for this particular project, would be best.</p>

<p>So far I have:</p>

<p>Advantages for in Code:</p>

<ul>
<li>Easier to maintain - don't need to run a SQL script to update queries</li>
<li>Easier to port to another DB - no procs to port</li>
</ul>

<p>Advantages for Stored Procs:</p>

<ul>
<li>Performance</li>
<li>Security</li>
</ul>

[{'answer_id': 15149, 'author': 'Stu', 'author_id': 414, 'author_profile': 'https://Stackoverflow.com/users/414', 'pm_score': 5, 'selected': False, 'text': '<p>The performance advantage for stored procedures is often negligable.</p>\n\n<p>More advantages for stored procedures:</p>\n\n<ul>\n<li>Prevent reverse engineering (if created With Encryption, of course)</li>\n<li>Better centralization of database access </li>\n<li>Ability to change data model transparently (without having to deploy new clients); especially handy if multiple programs access the same data model</li>\n</ul>\n'}, {'answer_id': 15151, 'author': 'mbillard', 'author_id': 810, 'author_profile': 'https://Stackoverflow.com/users/810', 'pm_score': 4, 'selected': False, 'text': "<p>Stored procedures.</p>\n\n<p>If an error slips or the logic changes a bit, you do not have to recompile the project. Plus, it allows access from different sources, not just the one place you coded the query in your project.</p>\n\n<p>I don't think it is harder to maintain stored procedures, you should not code them directly in the database but in separate files first, then you can just run them on whatever DB you need to set-up.</p>\n"}, {'answer_id': 15152, 'author': 'John Sheehan', 'author_id': 1786, 'author_profile': 'https://Stackoverflow.com/users/1786', 'pm_score': 3, 'selected': False, 'text': "<p>I prefer keeping in them in code (using an ORM, not inline or ad-hoc) so they're covered by source control without having to deal with saving out .sql files.</p>\n\n<p>Also, stored procedures aren't inherently more secure. You can write a bad query with a sproc just as easily as inline. Parameterized inline queries can be just as secure as a sproc.</p>\n"}, {'answer_id': 15153, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 7, 'selected': False, 'text': '<p>This is being discussed on a few other threads here currently.  I\'m a consistent proponent of stored procedures, although some good arguments for Linq to Sql are being presented.</p>\n\n<p>Embedding queries in your code couples you tightly to your data model.  Stored procedures are a good form of contractual programming, meaning that a DBA has the freedom to alter the data model and the code in the procedure, so long as the contract represented by the stored procedure\'s inputs and outputs is maintained.</p>\n\n<p>Tuning production databases can be extremely difficult when the queries are buried in the code and not in one central, easy to manage location.</p>\n\n<p>[Edit] Here is another <a href="https://stackoverflow.com/questions/14530/linq-vs-stored-procedures#14549">current discussion</a></p>\n'}, {'answer_id': 15159, 'author': 'Rob Allen', 'author_id': 149, 'author_profile': 'https://Stackoverflow.com/users/149', 'pm_score': 5, 'selected': False, 'text': "<blockquote>\n  <p>Advantages for in Code:</p>\n  \n  <ul>\n  <li>Easier to maintain - don't need to run a SQL script to update queries</li>\n  <li>Easier to port to another DB - no procs to port</li>\n  </ul>\n</blockquote>\n\n<p>Actually, I think you have that backwards. IMHO, SQL in code is pain to maintain because:</p>\n\n<ul>\n<li>you end up repeating yourself in related code blocks</li>\n<li>SQL isn't supported as a language in many IDE's so you have just a series of un-error checked strings performing tasks for you</li>\n<li>changes in a data type, table name or constraint are far more prevalent than swapping out an entire databases for a new one</li>\n<li>your level of difficulty increases as your query grows in complexity </li>\n<li>and testing an inline query requires building the project</li>\n</ul>\n\n<p>Think of Stored Procs as methods you call from the database object - they are much easier to reuse, there is only one place to edit and in the event that you do change DB providers, the changes happen in your Stored Procs and not in your code.</p>\n\n<p>That said, the performance gains of stored procs is minimal as Stu said before me and you can't put a break point in a stored procedure (yet).</p>\n"}, {'answer_id': 15162, 'author': 'Eugene Katz', 'author_id': 1533, 'author_profile': 'https://Stackoverflow.com/users/1533', 'pm_score': 2, 'selected': False, 'text': "<p>One of the suggestions from a Microsoft TechEd sessions on security which I attended, to make all calls through stored procs and deny access directly to the tables.  This approach was billed as providing additional security.  I'm not sure if it's worth it just for security, but if you're already using stored procs, it couldn't hurt.</p>\n"}, {'answer_id': 15173, 'author': 'Andrew G. Johnson', 'author_id': 428190, 'author_profile': 'https://Stackoverflow.com/users/428190', 'pm_score': 2, 'selected': False, 'text': '<p>Definitely easier to maintain if you put it in a stored procedure.  If there\'s difficult logic involved that will potentially change in the future it is definitely a good idea to put it in the database when you have multiple clients connecting.  For example I\'m working on an application right now that has an end user web interface and an administrative desktop application, both of which share a database (obviously) and I\'m trying to keep as much logic on the database as possible.  This is a perfect example of the <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="nofollow noreferrer">DRY principle</a>.</p>\n'}, {'answer_id': 15174, 'author': 'SQLMenace', 'author_id': 740, 'author_profile': 'https://Stackoverflow.com/users/740', 'pm_score': 3, 'selected': False, 'text': '<p>Think of it this way</p>\n\n<p>You have 4 webservers and a bunch of windows apps which use the same SQL code\nNow you realized there is a small problem with the SQl code\nso do you rather......\nchange the proc in 1 place\nor\npush the code to all the webservers, reinstall all the desktop apps(clickonce might help) on all the windows boxes</p>\n\n<p>I prefer stored procs</p>\n\n<p>It is also easier to do performance testing against a proc, put it in query analyzer\nset statistics io/time on\nset showplan_text on and voila</p>\n\n<p>no need to run profiler to see exactly what is being called</p>\n\n<p>just my 2 cents</p>\n'}, {'answer_id': 15181, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 3, 'selected': False, 'text': '<p>You list 2 pro-points for sprocs:</p>\n\n<p>Performance - not really.  In Sql 2000 or greater the query plan optimisations are pretty good, and cached. I\'m sure that Oracle etc do similar things.  I don\'t think there\'s a case for sprocs for performance any more.</p>\n\n<p>Security? Why would sprocs be more secure? Unless you have a pretty unsecured database anyway all the access is going to be from your DBAs or via your application. Always parametrise all queries - never inline something from user input and you\'ll be fine.</p>\n\n<p>That\'s best practice for performance anyway.</p>\n\n<p>Linq is definitely the way I\'d go on a new project right now. See this <a href="https://stackoverflow.com/questions/14530/linq-vs-stored-procedures#14531">similar post</a>.</p>\n'}, {'answer_id': 15185, 'author': 'Rick', 'author_id': 1752, 'author_profile': 'https://Stackoverflow.com/users/1752', 'pm_score': 4, 'selected': False, 'text': "<p>I fall on the <strong><em>code</em></strong> side.  We build data access layer that's used by all all the apps (both web and client), so it's DRY from that perspective.  It simplifies the database deployment because we just have to make sure the table schema's are correct.  It simplifies code maintenance because we don't have to look at source code and the database.  </p>\n\n<p>I don't have much problem with the tight coupling with the data model because I don't see where it's possible to really break that coupling.  An application and its data are inherently coupled.</p>\n"}, {'answer_id': 15193, 'author': 'Matthew Farwell', 'author_id': 1836, 'author_profile': 'https://Stackoverflow.com/users/1836', 'pm_score': 4, 'selected': False, 'text': "<p><strong>Advantages for Stored procedures</strong>:</p>\n\n<p>More easily code reviewed.</p>\n\n<p>Less coupled, therefore more easily tested.</p>\n\n<p>More easily tuned.</p>\n\n<p>Performance is generally better, from the point of view of network traffic - if you have a cursor, or similar, then there aren't multiple trips to the database</p>\n\n<p>You can protect access to the data more easily, remove direct access to the tables, enforce security through the procs - this also allows you to find relatively quickly any code that updates a table.</p>\n\n<p>If there are other services involved (such as Reporting services), you may find it easier to store all of your logic in a stored procedure, rather than in code, and having to duplicate it</p>\n\n<p><strong>Disadvantages:</strong></p>\n\n<p>Harder to manage for the developers: version control of the scripts: does everyone have their own database, is the version control system integrated with the database and IDE?</p>\n"}, {'answer_id': 15201, 'author': 'Seibar', 'author_id': 357, 'author_profile': 'https://Stackoverflow.com/users/357', 'pm_score': 2, 'selected': False, 'text': "<p>Stored Procedures are <em>MORE</em> maintainable because:</p>\n\n<ul>\n<li>You don't have to recompile your C# app whenever you want to change some SQL</li>\n<li>You end up reusing SQL code. </li>\n</ul>\n\n<p>Code repetition is the <em>worst</em> thing you can do when you're trying to build a maintainable application!</p>\n\n<p>What happens when you find a logic error that needs to be corrected in multiple places? You're more apt to forget to change that last spot where you copy &amp; pasted your code.</p>\n\n<p>In my opinion, the performance &amp; security gains are an added plus. <strong>You can still write insecure/inefficient SQL stored procedures.</strong></p>\n\n<blockquote>\n  <p>Easier to port to another DB - no procs to port</p>\n</blockquote>\n\n<p>It's not very hard to script out all your stored procedures for creation in another DB. In fact - it's <em>easier</em> than exporting your tables because there are no primary/foreign keys to worry about.</p>\n"}, {'answer_id': 15206, 'author': 'Seibar', 'author_id': 357, 'author_profile': 'https://Stackoverflow.com/users/357', 'pm_score': 1, 'selected': False, 'text': '<p>@Keith</p>\n\n<blockquote>\n  <p>Security? Why would sprocs be more secure?</p>\n</blockquote>\n\n<p>Stored procedures offer inherent protection from <a href="http://en.wikipedia.org/wiki/SQL_injection" rel="nofollow noreferrer">SQL Injection</a> attacks.</p>\n\n<p>However, you\'re not completely protected because you can still write stored procedures that are vulnerable to such attacks (i.e. dynamic SQL in a stored proc).</p>\n'}, {'answer_id': 15226, 'author': 'Guy', 'author_id': 1463, 'author_profile': 'https://Stackoverflow.com/users/1463', 'pm_score': 3, 'selected': False, 'text': "<p>@Keith</p>\n\n<blockquote>\n  <p>Security? Why would sprocs be more secure?</p>\n</blockquote>\n\n<p>As suggested by Komradekatz, you can disallow access to tables (for the username/password combo that connects to the DB) and allow SP access only. That way if someone gets the username and password to your database they can execute SP's but can't access the tables or any other part of the DB.</p>\n\n<p>(Of course executing sprocs may give them all the data they need but that would depend on the sprocs that were available. Giving them access to the tables gives them access to everything.)</p>\n"}, {'answer_id': 15253, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 2, 'selected': False, 'text': "<p>@Terrapin - sprocs are just as vulnerable to injection attacks. As I said:</p>\n\n<blockquote>\n  <p>Always parametrise all queries - never inline something from user input and you'll be fine.</p>\n</blockquote>\n\n<p>That goes for sprocs and dynamic Sql.</p>\n\n<p>I'm not sure not recompiling your app is an advantage. I mean, you have run your unit tests against that code (both application and DB) before going live again anyway.</p>\n\n<hr>\n\n<p>@Guy - yes you're right, sprocs do let you control application users so that they can only perform the sproc, not the underlying action. </p>\n\n<p>My question would be: if all the access it through your app, using connections and users with limited rights to update/insert etc, does this extra level add security or extra administration?</p>\n\n<p>My opinion is very much the latter. If they've compromised your application to the point where they can re-write it they have plenty of other attacks they can use.</p>\n\n<p>Sql injections can still be performed against those sprocs if they dynamically inline code, so the golden rule still applies, all user input must always be parametrised.</p>\n"}, {'answer_id': 15277, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 8, 'selected': True, 'text': '<p>I am not a fan of stored procedures</p>\n\n<blockquote>\n  <p>Stored Procedures are MORE maintainable because:\n     * You don\'t have to recompile your C# app whenever you want to change some SQL</p>\n</blockquote>\n\n<p>You\'ll end up recompiling it anyway when datatypes change, or you want to return an extra column, or whatever. The number of times you can \'transparently\' change the SQL out from underneath your app is pretty small on the whole</p>\n\n<blockquote>\n  <ul>\n  <li>You end up reusing SQL code.</li>\n  </ul>\n</blockquote>\n\n<p>Programming languages, C# included, have this amazing thing, called a function. It means you can invoke the same block of code from multiple places! Amazing! You can then put the re-usable SQL code inside one of these, or if you want to get really high tech, you can use a library which does it for you. I believe they\'re called Object Relational Mappers, and are pretty common these days.</p>\n\n<blockquote>\n  <p>Code repetition is the worst thing you can do when you\'re trying to build a maintainable application!</p>\n</blockquote>\n\n<p>Agreed, which is why storedprocs are a bad thing. It\'s much easier to refactor and decompose (break into smaller parts) code into functions than SQL into... blocks of SQL?</p>\n\n<blockquote>\n  <p>You have 4 webservers and a bunch of windows apps which use the same SQL code Now you realized there is a small problem with the SQl code so do you rather...... change the proc in 1 place or push the code to all the webservers, reinstall all the desktop apps(clickonce might help) on all the windows boxes</p>\n</blockquote>\n\n<p>Why are your windows apps connecting directly to a central database? That seems like a HUGE security hole right there, and bottleneck as it rules out server-side caching. Shouldn\'t they be connecting via a web service or similar to your web servers?</p>\n\n<p>So, push 1 new sproc, or 4 new webservers?</p>\n\n<p>In this case it <em>is</em> easier to push one new sproc, but in my experience, 95% of \'pushed changes\' affect the code and not the database. If you\'re pushing 20 things to the webservers that month, and 1 to the database, you hardly lose much if you instead push 21 things to the webservers, and zero to the database.</p>\n\n<blockquote>\n  <p>More easily code reviewed.</p>\n</blockquote>\n\n<p>Can you explain how? I don\'t get this. Particularly seeing as the sprocs probably aren\'t in source control, and therefore can\'t be accessed via web-based SCM browsers and so on.</p>\n\n<h2>More cons:</h2>\n\n<p>Storedprocs live in the database, which appears to the outside world as a black box. Simple things like wanting to put them in source control becomes a nightmare.</p>\n\n<p>There\'s also the issue of sheer effort. It might make sense to break everything down into a <a href="http://ptrthomas.wordpress.com/2006/06/06/java-call-stack-from-http-upto-jdbc-as-a-picture/" rel="noreferrer">million tiers</a> if you\'re trying to justify to your CEO why it just cost them 7 million dollars to build some forums, but otherwise creating a storedproc for every little thing is just extra donkeywork for no benefit.</p>\n'}, {'answer_id': 15297, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>Use your app code as what it does best: handle logic.<br>\nUser your database for what it does best: store data.  </p>\n\n<p>You can debug stored procedures but you will find easier to debug and maintaing logic in code.\nUsually you will end recompiling your code every time you change the database model.</p>\n\n<p>Also stored procedures with optional search parameters are very inneficient because you have to specify in advance all the possible parameters and complex searches are sometimes not possible because you cant predict how many times a parameter is going to be repeated in the seach. </p>\n'}, {'answer_id': 15766, 'author': 'MaseBase', 'author_id': 1888, 'author_profile': 'https://Stackoverflow.com/users/1888', 'pm_score': 1, 'selected': False, 'text': "<p>SQL injection attacks are on the upswing. It's very easy for someone to find this code and run injection attacks on your website. You must always <em><strong>always</strong></em> parameterize your queries. It's best to never run exec(@x) on a dynamic SQL query. It's just not a great idea to use inline SQL ever, IMO.</p>\n\n<p>Stored Procedures, as argued by some, are a hassle because they are another set of items to maintain separate from your code. But they are reusable and if you end up finding a bug in your queries, you can at fix them without recompiling.</p>\n"}, {'answer_id': 16779, 'author': 'Preston', 'author_id': 2006, 'author_profile': 'https://Stackoverflow.com/users/2006', 'pm_score': 1, 'selected': False, 'text': "<p>I'd like to cast another vote for using stored procs (despite the hassle they can introduce when it comes to maintenance and versioning) as a way to restrict direct access to the underlying tables for better security.</p>\n"}, {'answer_id': 35340, 'author': 'Natron', 'author_id': 3682, 'author_profile': 'https://Stackoverflow.com/users/3682', 'pm_score': 3, 'selected': False, 'text': "<p>I like stored procs, dont know how many times I was able to make a change to an application using a stored procedure which didn't produce any downtime to the application.</p>\n\n<p>Big fan of Transact SQL, tuning large queries have proven to be very useful for me. Haven't wrote any inline SQL in about 6 years!</p>\n"}, {'answer_id': 46128, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': "<p>In some circumstances, dynamically created sql in code can have better performance than a stored proc. If you have created a stored proc (let's say sp_customersearch) that gets extremely complicated with dozens of parameters because it must be very flexible, you can probably generate a much simpler sql statement in code at runtime. </p>\n\n<p>One could argue that this simply moves some processing from SQL to the web server, but in general that would be a good thing. </p>\n\n<p>The other great thing about this technique is that if you're looking in SQL profiler you can see the query you generated and debug it much easier than seeing a stored proc call with 20 parameters come in.</p>\n"}, {'answer_id': 46192, 'author': 'yukondude', 'author_id': 726, 'author_profile': 'https://Stackoverflow.com/users/726', 'pm_score': 2, 'selected': False, 'text': "<p>Something that I haven't seen mentioned thus far: the people who know the database best aren't always the people that write the application code. Stored procedures give the database folks a way to interface with programmers that don't really want to learn that much about SQL. Large--and especially legacy--databases aren't the easiest things to completely understand, so programmers might just prefer a simple interface that gives them what they need: let the DBAs figure out how to join the 17 tables to make that happen.</p>\n\n<p>That being said, the languages used to write stored procedures (PL/SQL being a notorious example) are pretty brutal. They typically don't offer any of the niceties you'd see in today's popular imperative, OOP, or functional languages. Think COBOL.</p>\n\n<p>So, stick to stored procedures that merely abstract away the relational details rather than those that contain business logic.</p>\n"}, {'answer_id': 83948, 'author': 'Tom H', 'author_id': 5696608, 'author_profile': 'https://Stackoverflow.com/users/5696608', 'pm_score': 3, 'selected': False, 'text': '<p>When it comes to security, stored procedures are much more secure. Some have argued that all access will be through the application anyway. The thing that many people are forgetting is that most security breaches come from inside a company. Think about how many developers know the "hidden" user name and password for your application?</p>\n\n<p>Also, as MatthieuF pointed out, performance can be much improved due to fewer round trips between the application (whether it\'s on a desktop or web server) and the database server.</p>\n\n<p>In my experience the abstraction of the data model through stored procedures also vastly improves maintainability. As someone who has had to maintain many databases in the past, it\'s such a relief when confronted with a required model change to be able to simply change a stored procedure or two and have the change be completely transparent to ALL outside applications. Many times your application isn\'t the only one pointed at a database - there are other applications, reporting solutions, etc. so tracking down all of those affected points can be a hassle with open access to the tables.</p>\n\n<p>I\'ll also put checks in the plus column for putting the SQL programming in the hands of those who specialize in it, and for SPs making it much easier to isolate and test/optimize code.</p>\n\n<p>The one downside that I see is that many languages don\'t allow the passing of table parameters, so passing an unknown number data values can be annoying, and some languages still can\'t handle retrieving multiple resultsets from a single stored procedure (although the latter doesn\'t make SPs any worse than inline SQL in that respect).</p>\n'}, {'answer_id': 131926, 'author': 'computinglife', 'author_id': 17224, 'author_profile': 'https://Stackoverflow.com/users/17224', 'pm_score': 5, 'selected': False, 'text': "<p><strong>CON</strong></p>\n\n<p>I find that doing lots of processing inside stored procedures would make your DB server a single point of inflexibility, when it comes to scaling your act. </p>\n\n<p>However doing all that crunching in your program as opposed to the sql-server,  <em>might</em> allow you to scale more if you have multiple servers that runs your code. Of-course this does not apply to stored procs that only does the normal fetch or update but to ones that perform more processing like looping over datasets. </p>\n\n<p><strong>PROS</strong></p>\n\n<ol>\n<li>Performance for what it may be worth (avoids query parsing by DB driver / plan recreation etc)</li>\n<li>Data manipulation is not embedded in the C/C++/C# code which means I have less low level code to look through. SQL is less verbose and easier to look through when listed separately. </li>\n<li>Due to the separation folks are able to find and reuse SQL code much easier.</li>\n<li>Its easier to change things when schema changes - you just have to give the same output to the code and it will work just fine</li>\n<li>Easier to port to a different database. </li>\n<li>I can list individual permissions on my stored procedures and control access at that level too.</li>\n<li>I can profile my data query/ persistence code separate from my data transformation code.</li>\n<li>I can implement changeable conditions in my stored procedure and it would be easy to customize at a customer site. </li>\n<li>It becomes easier to use some automated tools to convert my schema and statements together rather than when it is embedded inside my code where I would have to hunt them down.</li>\n<li>Ensuring best practices for data access is easier when you have all your data access code inside a single file - I can check for queries that access the non performant table or that which uses a higher level of serialization or select *'s in the code etc. </li>\n<li>It becomes easier to find schema changes / data manipulation logic changes when all of it is listed in one file. </li>\n<li>It becomes easier to do search and replace edits on SQL when they are in the same place e.g. change / add transaction isolation statements for all stored procs. </li>\n<li>I and the DBA guy find that having a separate SQL file is easier / convenient when the DBA has to review my SQL stuff. </li>\n<li>Lastly you don't have to worry about SQL injection attacks because some lazy member of your team did not use parametrized queries when using embedded sqls.</li>\n</ol>\n"}, {'answer_id': 132041, 'author': 'Bryan', 'author_id': 22033, 'author_profile': 'https://Stackoverflow.com/users/22033', 'pm_score': 0, 'selected': False, 'text': "<p>I have yet to find a good way of easily maintaining stored procs in source control that makes it as seamless as the code base.  It just doesn't happen.  This alone makes putting the SQL in your code worthwhile for me.  Performance differences are negligible on modern systems.</p>\n"}, {'answer_id': 142815, 'author': 'MattMcKnight', 'author_id': 8136, 'author_profile': 'https://Stackoverflow.com/users/8136', 'pm_score': 1, 'selected': False, 'text': '<p>Stored procedures are the worst when they are used to stand in-between applications and the database.  Many of the reasons for their use stated above are better handled by views.</p>\n\n<p>The security argument is spurious.  It just moves the security problem from the application to the database.  Code is code. I have seen stored procedures that take in SQL from the applications and use it build queries that were subject to SQL injection attacks.</p>\n\n<p>In general, they tend to create a rift between so-called database developers and so-called application developers. In reality, all of the code that is written is application code, it is only a difference of the execution context. </p>\n\n<p>Using rich SQL generation libraries like LINQ, Rails ActiveRecord, or Hibernate/NHibernate makes development faster. Inserting stored procedures in the mix slows it down.</p>\n'}, {'answer_id': 146437, 'author': 'Constantin', 'author_id': 20310, 'author_profile': 'https://Stackoverflow.com/users/20310', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Smaller logs</strong></p>\n\n<p>Another minor pro for stored procedures that has not been mentioned: when it comes to SQL traffic, sp-based data access generates <em>much</em> less traffic. This becomes important when you monitor traffic for analysis and profiling - the logs will be much smaller and readable.</p>\n'}, {'answer_id': 146477, 'author': 'HLGEM', 'author_id': 9034, 'author_profile': 'https://Stackoverflow.com/users/9034', 'pm_score': 2, 'selected': False, 'text': "<p>I'm firmly on the side of stored procs assuming you don't cheat and use dynamic SQL in the stored proc. First, using stored procs allows the dba to set permissions at the stored proc level and not the table level. This is critical not only to combating SQL injection attacts but towards preventing insiders from directly accessing the database and changing things. This is a way to help prevent fraud. No database that contains personal information (SSNs, Credit card numbers, etc) or that in anyway creates financial transactions should ever be accessed except through strored procedures. If you use any other method you are leaving your database wide open for individuals in the company to create fake financial transactions or steal data that can be used for identity theft.</p>\n\n<p>Stored procs are also far easier to maintain and performance tune than SQL sent from the app. They also allow the dba a way to see what the impact of a database structural change will have on the way the data is accessed. I've never met a good dba who would allow dynamic access to the database. </p>\n"}, {'answer_id': 164634, 'author': 'Timothy Lee Russell', 'author_id': 12919, 'author_profile': 'https://Stackoverflow.com/users/12919', 'pm_score': 1, 'selected': False, 'text': '<p>I prefer to use an O/R Mapper such as <a href="http://www.llblgen.com" rel="nofollow noreferrer">LLBLGen Pro</a>.</p>\n\n<p>It gives you relatively painless database portability, allows you to write your database access code in the same language as your application using strongly-typed objects and, in my opinion, allows you more flexibility in how you work with the data that you pull back.</p>\n\n<p>Actually, being able to work with strongly-typed objects is reason enough to use an O/R Mapper.</p>\n'}, {'answer_id': 214085, 'author': 'Tom Anderson', 'author_id': 13502, 'author_profile': 'https://Stackoverflow.com/users/13502', 'pm_score': 2, 'selected': False, 'text': '<p>I am a huge supporter of code over SPROC\'s. The number one reasons is keeping the code tightly coupled, then a close second is the ease of source control without a lot of custom utilities to pull it in.</p>\n\n<p>In our DAL if we have very complex SQL statements, we generally include them as resource files and update them as needed (this could be a separate assembly as well, and swapped out per db, etc...).</p>\n\n<p>This keeps our code and our sql calls stored in the same version control, without "forgetting" to run some external applications for updating.</p>\n'}, {'answer_id': 229568, 'author': 'Libor', 'author_id': 30777, 'author_profile': 'https://Stackoverflow.com/users/30777', 'pm_score': 0, 'selected': False, 'text': '<p>Preference of stored procedures because:\n- enable fix some  data related issues in production while system is running (this is num. one for me)\n- clean contract definition between DB and program (clean separation of concerns)\n- better portability to different DB vendor (if written well than code change is usually only on SP side).\n- better positioned for performance tuning</p>\n\n<p>Cons - problematic in case WHERE clause has great variation in used conditions and high performance is needed.  </p>\n'}, {'answer_id': 229708, 'author': 'huo73', 'author_id': 15657, 'author_profile': 'https://Stackoverflow.com/users/15657', 'pm_score': 6, 'selected': False, 'text': "<p>In my opinion you can't vote for yes or no on this question. It totally depends on the design of your application. </p>\n\n<p>I totally vote against the use of SPs in an 3-tier environment, where you have an application server in front. In this kind of environment your application server is there to run your business logic. If you additionally use SPs you start distributing your implementation of business logic all over your system and it will become very unclear who is responsible for what. Eventually you will end up with an application server that will basically do nothing but the following:</p>\n\n<pre><code>(Pseudocode)\n\nFunction createOrder(Order yourOrder) \nBegin\n  Call SP_createOrder(yourOrder)\nEnd\n</code></pre>\n\n<p>So in the end you have your middle tier running on this very cool 4 Server cluster each of them equipped with 16 CPUs and it will actually do nothing at all! What a waste!</p>\n\n<p>If you have a fat gui client that directly connects to your DB or maybe even more applications it's a different story. In this situation SPs can serve as some sort of pseudo middle tier that decouples your application from the data model and offers a controllable access.</p>\n"}, {'answer_id': 229970, 'author': 'Dave Sherohman', 'author_id': 18914, 'author_profile': 'https://Stackoverflow.com/users/18914', 'pm_score': 2, 'selected': False, 'text': '<p>I generally write OO code.  I suspect that most of you probably do, too.  In that context, it seems obvious to me that all of the business logic - including SQL queries - belongs in the class definitions.  Splitting up the logic such that part of it resides in the object model and part is in the database is no better than putting business logic into the user interface.</p>\n\n<p>Much has been said in earlier answers about the security benefits of stored procs.  These fall into two broad categories:</p>\n\n<p>1)  Restricting direct access to the data.  This definitely is important in some cases and, when you encounter one, then stored procs are pretty much your only option.  In my experience, such cases are the exception rather than the rule, however.</p>\n\n<p>2)  SQL injection/parametrized queries.  This objection is a red herring.  Inline SQL - even dynamically-generated inline SQL - can be just as fully parametrized as any stored proc and it can be done just as easily in any modern language worth its salt.  There is no advantage either way here.  ("Lazy developers might not bother with using parameters" is not a valid objection.  If you have developers on your team who prefer to just concatenate user data into their SQL instead of using parameters, you first try to educate them, then you fire them if that doesn\'t work, just like you would with developers who have any other bad, demonstrably detrimental habit.)</p>\n'}, {'answer_id': 240010, 'author': 'ObiWanKenobi', 'author_id': 31802, 'author_profile': 'https://Stackoverflow.com/users/31802', 'pm_score': 1, 'selected': False, 'text': '<p>My vote for stored procedures; as an abstraction layer close to the data, efficient with sets, reusable by many "clients" (client languages). The T-SQL language is a bit primitive (and I guess that\'s what most of the C# guys here at SO have been exposed to), but Oracle\'s PL/SQL is on par with any modern programming language.</p>\n\n<p>As for version control, just put the stored procedure code in text files under version control, then run the scripts to create the procs in the database.</p>\n'}, {'answer_id': 350760, 'author': 'Theresa', 'author_id': 39355, 'author_profile': 'https://Stackoverflow.com/users/39355', 'pm_score': 2, 'selected': False, 'text': "<p>We use stored procedures with Oracle DB's where I work now.  We also use Subversion.  All the stored procedures are created as .pkb &amp; .pks files and saved in Subversion.  I've done in-line SQL before and it is a pain!  I much prefer the way we do it here.  Creating and testing new stored procedures is much easier than doing it in your code.</p>\n\n<p>Theresa</p>\n"}, {'answer_id': 757267, 'author': 'kishore', 'author_id': 76933, 'author_profile': 'https://Stackoverflow.com/users/76933', 'pm_score': 0, 'selected': False, 'text': '<p>Pros to stored procedures\n1). Improved security as the SQL in stored procedure is static in nature(Mostly). This will protect against SQL injection.\n2). Reusability. If there is a need to return the same data for multiple applications/components, this may be a better choice instead of repeating the SQL statements.\n3). Reduces calls between client and database server.</p>\n\n<p>I am not sure about other databases but you can create stored procedures in host languages in db2 on mainframe which makes them very powerful. </p>\n'}, {'answer_id': 966343, 'author': 'Neil', 'author_id': 44869, 'author_profile': 'https://Stackoverflow.com/users/44869', 'pm_score': 0, 'selected': False, 'text': '<p>Foot firmly in the "Stored Procs are bad for CRUD/business logic use" camp. I understand the need in reporting, data import, etc</p>\n\n<p><a href="http://gratdevel.blogspot.com/2009/06/stored-procs-vs-well-not-stored-procs.html" rel="nofollow noreferrer">Write up here...</a></p>\n'}, {'answer_id': 966585, 'author': 'Justin', 'author_id': 113141, 'author_profile': 'https://Stackoverflow.com/users/113141', 'pm_score': -1, 'selected': False, 'text': '<p>For Microsoft SQL Server you should use stored procedures wherever possible to assist with execution plan caching and reuse. Why do you want to optimise plan re-use? Because the generation of execution plans is fairly expensive to do.</p>\n\n<p>Although the caching and reuse of execution plans for ad-hoc queries has improved significantly in later editions of SQL server (especially 2005 and 2008) there are still far fewer issues with plan reuse when dealing with stored procedures than there are for ad-hoc queries. For example, SQL server will only re-use an execution plan if the plan text matches <strong>exactly</strong> - right down to comments and white space, for example, if each of the following lines of SQL were to be executed independently, none of them would use the same execution plan:</p>\n\n<pre><code>SELECT MyColumn FROM MyTable WHERE id = @id\nselect MyColumn from MyTable WHERE id = @id\nSELECT MyColumn  FROM MyTable WHERE id = @id\nSELECT MyColumn FROM MyTable WHERE id = @id -- "some comment"\nSELECT MyColumn FROM MyTable WHERE id = @id -- "some other comment"\n</code></pre>\n\n<p>On top of this, if you don\'t explicitly specify the types of your parameters then there is a good chance that SQL Server might get it wrong, for example if you executed the above query with the input 4, then SQL Server will parametrise the query with @id as a SMALLINT (or possibly a TINYINT), and so if you then execute the same query with an @id of say 4000, SQL Server will parametrise it as an INT, and wont reuse the same cache.</p>\n\n<p>I think there are also some other issues, and in honesty most of them can probably be worked around - especially with later editions of SQL Server, but stored procedures generally offer you more control.</p>\n'}, {'answer_id': 996265, 'author': 'JeffO', 'author_id': 61339, 'author_profile': 'https://Stackoverflow.com/users/61339', 'pm_score': 0, 'selected': False, 'text': "<p>Programmers want the code in their app.  DBA's want it in the database. </p>\n\n<p>If you have both, you can divide the work between the two by using stored procedures and the programmers don't have to worry about how all those tables join together etc. (Sorry, I know you want to be in control of everything.).</p>\n\n<p>We have a 3rd party application that allows custom reports to be created on a View or Stored Procedure in the database. If I put all of my logic in the code in another application, I could not reuse it. If you are in a situation where you write all of the apps using the database, this isn't a problem.</p>\n"}, {'answer_id': 2348397, 'author': 'Jiho Han', 'author_id': 25856, 'author_profile': 'https://Stackoverflow.com/users/25856', 'pm_score': 0, 'selected': False, 'text': '<p>Stored procedures can go out of sync between database and source control system more easily than code.  The application code can too, but it\'s less likely when you have continuous integration.</p>\n\n<p>Database being what it is, people inevitably make changes to production databases, just to get out of the woods for the moment.  Then forget to sync it across the environments and source control system.  Sooner or later, production db becomes the de facto record rather than the source control system - you get into a situation where you cannot remove any sprocs, because you don\'t know whether it\'s being used.</p>\n\n<p>A good process should only allow changes to the production only through proper channels, so that you should be able to rebuild a database from scratch from the source control system (sans data).  But I\'m just saying just because it can be done and does get done - changes are made to production database at the heat of moment, between calls from yelling clients, managers breathing down your neck, etc.</p>\n\n<p>Running ad-hoc queries is awkward with stored procedures - it\'s easier done with dynamic sql (or ORM), which may be the biggest drawback to using stored procedures for myself.</p>\n\n<p>Stored procedures, on the other hand is nice in situations where you make a change but doesn\'t require re-deployment of app code.  It also allows you to shape your data before sending it over the network where sql in code might have to make multiple calls to retrieve than shape it (although there are now ways to run multiple sql statements and return multiple result sets in a single "call", as in MARS in ADO.NET), resulting in probably more data travelling through your network.</p>\n\n<p>I don\'t buy any other arguments regarding performance and security though.  Either can be good or bad, and equally controlled.</p>\n'}, {'answer_id': 2996041, 'author': 'SiN', 'author_id': 339423, 'author_profile': 'https://Stackoverflow.com/users/339423', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m not a big fan of stored procedures, but I use them in one condition:</p>\n\n<p>When the query is pretty huge, it\'s better to store it in the database as a stored procedure instead of sending it from the code. That way, instead of sending huge ammounts of string characters from the application server to the database, only the <code>"EXEC SPNAME"</code> command will be sent.</p>\n\n<p>This is overkill when the database server and the web server are not on the same network (For example, internet communication). And even if that\'s not the case, too much stress means a lot of wasted bandwith.</p>\n\n<p>But man, they\'re so terrible to manage. I avoid them as much as I can.</p>\n'}, {'answer_id': 4112218, 'author': 'yfeldblum', 'author_id': 12349, 'author_profile': 'https://Stackoverflow.com/users/12349', 'pm_score': 0, 'selected': False, 'text': '<p>Your programming language and application framework are likely:</p>\n\n<ul>\n<li>high-level, especially as compared with SQL</li>\n<li>easy to version and deploy via automated processes, especially as compared with SQL</li>\n</ul>\n\n<p>If these two conditions are two, then skip the stored procedures.</p>\n'}, {'answer_id': 5417926, 'author': 'Gagnaire Eric', 'author_id': 669595, 'author_profile': 'https://Stackoverflow.com/users/669595', 'pm_score': 2, 'selected': False, 'text': "<p>A SQL stored proc doesn't increase the performance of the query</p>\n"}, {'answer_id': 7123283, 'author': 'Nicola Musatti', 'author_id': 838975, 'author_profile': 'https://Stackoverflow.com/users/838975', 'pm_score': 1, 'selected': False, 'text': "<p>One point I did not find in the other answers is the following:</p>\n\n<p>If in your environment the database and its schema are the heart of the architecture and applications have a more satellite role then it may make sense to make heavier use of stored procedures, which may help provide a level base for all the applications that need to access the DB, and thus induce less code repetition (e.g. are you sure that all your DB accessing applications will always be written in C# or other .NET languages?).</p>\n\n<p>If, on the other hand, the application has a more central role and the DB acts more as a backing store for the application, then it may be sensible to make less use of stored procedures and achieve reduced code repetition by providing a common persistence layer, possibly based on an ORM tool/framework.</p>\n\n<p>In both cases it's important that the DB is not considered a convenient repository for stored procedures. Keep them in source files within a version control system and try and automate their deployment as much as possible (this is actually valid for all schema related artifacts).</p>\n"}, {'answer_id': 7945739, 'author': 'Bilal Khan', 'author_id': 954974, 'author_profile': 'https://Stackoverflow.com/users/954974', 'pm_score': 2, 'selected': False, 'text': '<p>Well obviously using stored procedures has several advantages over constructing SQL in code.</p>\n\n<ol>\n<li>Your code implementation and SQL become independent of each other.</li>\n<li>Code is easier to read.</li>\n<li>Write once use many times.</li>\n<li>Modify once </li>\n<li>No need to give internal details to the programmer about the database. etc , etc.</li>\n</ol>\n'}, {'answer_id': 12691051, 'author': 'redej', 'author_id': 1712674, 'author_profile': 'https://Stackoverflow.com/users/1712674', 'pm_score': 0, 'selected': False, 'text': "<p>The biggest advantage of sproc in the place I work is that we have way less code to port to VB.NET (from VB6) when time comes. And it's WAY less code because we use sprocs for all our queries.</p>\n\n<p>Also it helps a lot when we need to update the queries instead of updating the VB code, re-compile and re-install it on all computers.</p>\n"}, {'answer_id': 21862016, 'author': 'Daniel 1.618', 'author_id': 2107989, 'author_profile': 'https://Stackoverflow.com/users/2107989', 'pm_score': 1, 'selected': False, 'text': '<p><strong>Nobody mentioned unit testing!</strong></p>\n\n<p>If you have a saveOrder method you can call several methods inside and create a unit test for each one of those but if you are only calling a store procedure there is no way to do that.</p>\n'}]
['https://Stackoverflow.com/questions/15142', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1463/']