<p>Assuming you can't use LINQ for whatever reason, is it a better practice to place your queries in stored procedures, or is it just as good a practice to execute <em>ad hoc</em> queries against the database (say, SQL Server for argument's sake)?</p>

[{'answer_id': 22914, 'author': 'EndangeredMassa', 'author_id': 106, 'author_profile': 'https://Stackoverflow.com/users/106', 'pm_score': 1, 'selected': False, 'text': '<p>Stored Procedures are great because they can be changed without a recompile. I would try to use them as often as possible.</p>\n\n<p>I only use ad-hoc for queries that are dynamically generated based on user input.</p>\n'}, {'answer_id': 22916, 'author': 'Seibar', 'author_id': 357, 'author_profile': 'https://Stackoverflow.com/users/357', 'pm_score': 2, 'selected': False, 'text': '<p>My answer <a href="https://stackoverflow.com/questions/15142/what-are-the-pros-and-cons-to-keeping-sql-in-stored-procs-versus-code#15206">from a different</a> post:\nStored 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': 22919, 'author': 'TheSmurf', 'author_id': 1975282, 'author_profile': 'https://Stackoverflow.com/users/1975282', 'pm_score': 0, 'selected': False, 'text': '<p>Depends what your goal is. If you want to retrieve a list of items and it happens once during your application\'s entire run for example, it\'s probably not worth the effort of using a stored procedure. On the other hand, a query that runs repeatedly and takes a (relatively) long time to execute is an excellent candidate for database storage, since the performance will be better.</p>\n\n<p>If your application lives almost entirely within the database, stored procedures are a no-brainer. If you\'re writing a desktop application to which the database is only tangentially important, ad-hoc queries may be a better option, as it <a href="https://stackoverflow.com/questions/22818/where-to-put-your-code-database-vs-application">keeps all of your code in one place</a>.</p>\n\n<p>@Terrapin: I think your assertion that the fact that you don\'t have to recompile your app to make modifications makes stored procedures a better option is a non-starter. There may be reasons to choose stored procedures over ad-hoc queries, but in the absence of anything else compelling, the compile issue seems like laziness rather than a real reason. </p>\n'}, {'answer_id': 22923, 'author': 'JamesSugrue', 'author_id': 1075, 'author_profile': 'https://Stackoverflow.com/users/1075', 'pm_score': 2, 'selected': False, 'text': '<p>There are persuasive arguments for both - stored procedures are all located in a central repository, but are (potentially) hard to migrate and ad hoc queries are easier to debug as they are with your code, but they can also be harder to find in the code.</p>\n\n<p>The argument that stored procedures are more efficient doesn\'t hold water anymore.\n<a href="http://weblogs.asp.net/fbouma/archive/2003/05/14/7008.aspx" rel="nofollow noreferrer">link text</a></p>\n\n<p>Doing a google for Stored Procedure vs Dynamic Query will show decent arguments either way and probably best for you to make your own decision...</p>\n'}, {'answer_id': 22929, 'author': 'SQLMenace', 'author_id': 740, 'author_profile': 'https://Stackoverflow.com/users/740', 'pm_score': 1, 'selected': False, 'text': "<p>Procs for the reasons mentioned by others and also it is easier to tune a proc with profiler or parts of a proc. This way you don't have to tell someone to run his app to find out what is being sent to SQL server</p>\n\n<p>If you do use ad-hoc queries make sure that they are parameterized</p>\n"}, {'answer_id': 22952, 'author': 'Webjedi', 'author_id': 1975, 'author_profile': 'https://Stackoverflow.com/users/1975', 'pm_score': 1, 'selected': False, 'text': "<p>Parametized SQL or SPROC...doesn't matter from a performance stand point...you can query optimize either one.</p>\n\n<p>For me the last remaining benefit of a SPROC is that I can eliminate a lot SQL rights management by only granting my login rights to execute sprocs...if you use Parametized SQL the login withing your connection string has a lot more rights (writing ANY kind of select statement on one of the tables they have access too for example).  </p>\n\n<p>I still prefer Parametized SQL though...</p>\n"}, {'answer_id': 22970, 'author': 'akmad', 'author_id': 1314, 'author_profile': 'https://Stackoverflow.com/users/1314', 'pm_score': 8, 'selected': True, 'text': "<p>In my experience writing mostly WinForms Client/Server apps these are the simple conclusions I've come to:</p>\n\n<p><strong>Use Stored Procedures:</strong></p>\n\n<ol>\n<li>For any complex data work.  If you're going to be doing something truly requiring a cursor or temp tables it's usually fastest to do it within SQL Server.</li>\n<li>When you need to lock down access to the data.  If you don't give table access to users (or role or whatever) you can be sure that the only way to interact with the data is through the SP's you create.</li>\n</ol>\n\n<p><strong>Use ad-hoc queries:</strong></p>\n\n<ol>\n<li>For CRUD when you don't need to restrict data access (or are doing so in another manner).</li>\n<li>For simple searches.  Creating SP's for a bunch of search criteria is a pain and difficult to maintain.  If you can generate a reasonably fast search query use that.</li>\n</ol>\n\n<p>In most of my applications I've used both SP's and ad-hoc sql, though I find I'm using SP's less and less as they end up being code just like C#, only harder to version control, test, and maintain.  I would recommend using ad-hoc sql unless you can find a specific reason not to.</p>\n"}, {'answer_id': 22975, 'author': 'AR.', 'author_id': 1354, 'author_profile': 'https://Stackoverflow.com/users/1354', 'pm_score': 2, 'selected': False, 'text': '<p>Some things to think about here: <a href="https://blog.codinghorror.com/who-needs-stored-procedures-anyways/" rel="nofollow noreferrer">Who Needs Stored Procedures, Anyways?</a></p>\n\n<p>Clearly it\'s a matter of your own needs and preferences, but one very important thing to think about when using ad hoc queries in a public-facing environment is security. Always parameterize them and watch out for the typical vulnerabilities like <a href="https://en.wikipedia.org/wiki/SQL_injection" rel="nofollow noreferrer">SQL-injection attacks</a>.</p>\n'}, {'answer_id': 22986, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 4, 'selected': False, 'text': '<p>Stored procedures represent a software contract that encapsulates the actions taken against the database.  The code in the procedures, and even the schema of the database itself can be changed without affecting compiled, deployed code, just so the inputs and outputs of the procedure remain the same.</p>\n\n<p>By embedding queries in your application, you are tightly coupling yourself to your data model.</p>\n\n<p>For the same reason, it is also not good practice to simply create stored procedures that are just CRUD queries against every table in your database, since this is still tight coupling.  The procedures should instead be bulky, coarse grained operations.</p>\n\n<p>From a security perspective, it is good practice to disallow db_datareader and db_datawriter from your application and only allow access to stored procedures.</p>\n'}, {'answer_id': 23008, 'author': 'Krantz', 'author_id': 2528, 'author_profile': 'https://Stackoverflow.com/users/2528', 'pm_score': 3, 'selected': False, 'text': "<p>Stored procedures are definitely the way to go...they are compiled, have execution plan before hand and you could do rights management on them. </p>\n\n<p>I do not understand this whole source control issue on stored procedure. You definitely can source control them, if only you are a little disciplined. </p>\n\n<p>Always start with a .sql file that is the source of your stored procedure. Put it in version control once you have written your code. The next time you want to edit your stored procedure get it from your source control than your database. If you follow this, you will have as good source control as your code.</p>\n\n<p>I would like to quote Tom Kyte from Oracle here...Here's his rule on where to write code...though a bit unrelated but good to know I guess.</p>\n\n<ol>\n<li>Start with stored procedures in PL/SQL...</li>\n<li>If you think something can't be done using stored procedure in PL/SQL, use Java stored procedure.</li>\n<li>If you think something can't be done using Java Stored procedure, consider Pro*c.</li>\n<li>If you think you can't achieve something using Pro*C, you might want to rethink what you need to get done.</li>\n</ol>\n"}, {'answer_id': 23039, 'author': 'Almond', 'author_id': 1603, 'author_profile': 'https://Stackoverflow.com/users/1603', 'pm_score': 2, 'selected': False, 'text': "<p>Store procedures should be used as much as possible, if your writing SQL into code your already setting yourself up for headaches in the futures. It takes about the same time to write a SPROC as it does to write it in code.</p>\n\n<p>Consider a query that runs great under a medium load but once it goes into fulltime production your badly optimized query hammers the system and brings it to a crawl. In most SQL servers you are not the only application/service that is using it. Your application has now brought a bunch of angry people at your door.</p>\n\n<p>If you have your queries in SPROCs you also allow your friendly DBA to manage and optimize with out recompiling or breaking your app. Remember DBA's are experts in this field, they know what to do and not do. It makes sense to utilise their greater knowledge!</p>\n\n<p>EDIT: someone said that recompile is a lazy excuse! yeah lets see how lazy you feel when you have to recompile and deploy your app to 1000's of desktops, all because the DBA has told you that your ad-hoc Query is eating up too much Server time!</p>\n"}, {'answer_id': 23065, 'author': 'Jakub Šturc', 'author_id': 2361, 'author_profile': 'https://Stackoverflow.com/users/2361', 'pm_score': 0, 'selected': False, 'text': "<p>My experience is that 90% of queries and/or stored procedures should not be written at all (at least by hand).</p>\n\n<p>Data access should be generated somehow automaticly. You can decide if you'd like to staticly generate procedures in compile time or dynamically at run time but when you want add column to the table (property to the object) you should modify only one file.</p>\n"}, {'answer_id': 23072, 'author': 'Tundey', 'author_id': 1453, 'author_profile': 'https://Stackoverflow.com/users/1453', 'pm_score': 1, 'selected': False, 'text': "<p>I haven't found any compelling argument for using ad-hoc queries. Especially those mixed up with your C#/Java/PHP code. </p>\n"}, {'answer_id': 23073, 'author': 'Jakub Šturc', 'author_id': 2361, 'author_profile': 'https://Stackoverflow.com/users/2361', 'pm_score': 2, 'selected': False, 'text': "<blockquote>\n  <p>someone said that recompile is a lazy excuse! yeah lets see how lazy you feel when you have to recompile and deploy your app to 1000's of desktops, all because the DBA has told you that your ad-hoc Query is eating up too much Server time!</p>\n</blockquote>\n\n<p>is it good system architecture if you let connect 1000 desktops directly to database?</p>\n"}, {'answer_id': 24000, 'author': 'Dave Ward', 'author_id': 60, 'author_profile': 'https://Stackoverflow.com/users/60', 'pm_score': 5, 'selected': False, 'text': "<p>I can't speak to anything other than SQL Server, but the performance argument is <strong>not</strong> significantly valid there unless you're on 6.5 or earlier.  SQL Server has been caching ad-hoc execution plans for roughly a decade now.</p>\n"}, {'answer_id': 24185, 'author': 'Almond', 'author_id': 1603, 'author_profile': 'https://Stackoverflow.com/users/1603', 'pm_score': -1, 'selected': False, 'text': "<blockquote>\n  <p>is it good system architecture if you\n  let connect 1000 desktops directly to\n  database?</p>\n</blockquote>\n\n<p>No it's obviously not, it's maybe a poor example but I think the point I was trying to make is clear, your DBA looks after your database infrastructure this is were their expertise is, stuffing SQL in code locks the door to them and their expertise.</p>\n"}, {'answer_id': 29642, 'author': 'garethm', 'author_id': 2219, 'author_profile': 'https://Stackoverflow.com/users/2219', 'pm_score': 2, 'selected': False, 'text': "<p>In our application, there is a layer of code that provides the content of the query (and is sometimes a call to a stored procedure). This allows us to:</p>\n\n<ul>\n<li>easily have all the queries under version control</li>\n<li>to make what ever changes are required to each query for different database servers</li>\n<li>eliminates repetition of the same query code through out our code</li>\n</ul>\n\n<p>Access control is implemented in the middle layer, rather than in the database, so we don't need stored procedures there. This is in some ways a middle road between ad hoc queries and stored procs.</p>\n"}, {'answer_id': 29669, 'author': 'Sander', 'author_id': 2928, 'author_profile': 'https://Stackoverflow.com/users/2928', 'pm_score': 0, 'selected': False, 'text': '<p>I prefer keeping all data <strong>access</strong> logic in the program code, in which the data access layer executes straight SQL queries. On the other hand, data <strong>management</strong> logic I put in the database in the form of triggers, stored procedures, custom functions and whatnot. An example of something I deem worthy of database-ifying is data generation - assume our customer has a FirstName and a LastName. Now, the user interface needs a DisplayName, which is derived from some nontrivial logic. For this generation, I create a stored procedure which is then executed by a trigger whenever the row (or other source data) is updated.</p>\n\n<p>There appears to be this somewhat common misunderstanding that the data access layer IS the database and everything about data and data access goes in there "just because". This is simply wrong but I see a lot of designs which derive from this idea. Perhaps this is a local phenomonon, though.</p>\n\n<p>I may just be turned off the idea of SPs after seeing so many badly designed ones. For example, one project I participated in used a set of CRUD stored procedures for every table and every possible query they encountered. In doing so they simply added another completely pointless layer. It is painful to even think about such things.</p>\n'}, {'answer_id': 29673, 'author': 'liammclennan', 'author_id': 2785, 'author_profile': 'https://Stackoverflow.com/users/2785', 'pm_score': 0, 'selected': False, 'text': "<p>These days I hardly ever use stored procedures. I only use them for complicated sql queries that can't easily be done in code. </p>\n\n<p>One of the main reasons is because stored procedures do not work as well with OR mappers. </p>\n\n<p>These days I think you need a very good reason to write a business application / information system that does not use some sort of OR mapper.</p>\n"}, {'answer_id': 105557, 'author': 'HLGEM', 'author_id': 9034, 'author_profile': 'https://Stackoverflow.com/users/9034', 'pm_score': 4, 'selected': False, 'text': "<p>I think this is a basic conflict between people who must maintain the database and people who develop the user interfaces. </p>\n\n<p>As a data person, I would not consider working with a database that is accessed through adhoc queries because they are difficult to effectively tune or manage. How can I know what affect a change to the schema will have? Additionally, I do not think users should ever be granted direct access to the database tables for security reasons (and I do not just mean SQL injection attacks, but also because it is a basic internal control to not allow direct rights and require all users to use only the procs designed for the app. This is to prevent possible fraud. Any financial system which allows direct insert, update or delete rights to tables is has a huge risk for fraud. This is a bad thing.). </p>\n\n<p>Databases are not object-oriented and code which seems good from an object-oriented perspective is can be extremely bad from a database perspective. </p>\n\n<p>Our developers tell us they are glad that all our databse access is through procs becasue it makes it much faster to fix a data-centered bug and then simply run the proc on the production environment rather than create a new branch of the code and recompile and reload to production. We require all our procs to be in subversion, so source control is not an issue at all. If it isn't in Subversion, it will periodically get dropped by the dbas, so there is no resistance to using Source Control.</p>\n"}, {'answer_id': 1063696, 'author': 'KuldipMCA', 'author_id': 130452, 'author_profile': 'https://Stackoverflow.com/users/130452', 'pm_score': 0, 'selected': False, 'text': "<p>Stored procedure work as block of code so in place of adhoc query it work fast.\nAnother thing is stored procedure give recompile option which the best part of\nSQL you just use this for stored procedures nothing like this in adhoc query.</p>\n\n<p>Some result in query and stored procedure are different that's my personal exp.\nUse cast and covert function for check this.</p>\n\n<p>Must use stored procedure for big projects to improve the performance.</p>\n\n<p>I had 420 procedures in my project and it's work fine for me. I work for last 3 years on this project.</p>\n\n<p>So use only procedures for any transaction.</p>\n"}, {'answer_id': 2761125, 'author': 'TimATX', 'author_id': 287562, 'author_profile': 'https://Stackoverflow.com/users/287562', 'pm_score': 1, 'selected': False, 'text': '<p>The sproc performance argument is moot - the 3 top RDBMs use query plan caching and have been for awhile. Its been documented... Or is 1995 still?</p>\n\n<p>However, embedding SQL in your app is a terrible design too - code maintenance seems to be a missing concept for many. </p>\n\n<p>If an application can start from scratch with an ORM (greenfield applications are far and few between!) its a great choice as your class model drives your DB model - and saves LOTS of time. </p>\n\n<p>If an ORM framework is not available we have taken a hybrid of approach of creating an SQL resource XML file to look up SQL strings as we need them (they are then cached by the resource framework). If the SQL needs any minor manipulation its done in code - if major SQL string manipulation is needed we rethink the approach.</p>\n\n<p>This hybrid approach lends to easy management by the developers (maybe we are the minority as my team is bright enough to read a query plan) and deployment is a simple checkout from SVN. Also, it makes switching RDBMs easier - just swap out the SQL resource file (not as easy as an ORM tool of course, but connecting to legacy systems or non-supported database this works)</p>\n'}]
['https://Stackoverflow.com/questions/22907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']