The advantages of stored procedures are not necessarily completely executed one by one using only sql

quote

Stored procedures are used every day, and the debate about using SQL statements in stored procedures has been ongoing. Personally, I think that using stored procedures is better than using SQL statements. I have organized some explanations:


Stored procedures are encapsulated by some SQL statements and control statements. A procedure, which resides in the database, can be called by a client application or from another procedure or trigger. Its arguments can be passed and returned. Similar to function procedures in an application, stored procedures can be called by name, and they also have input and output parameters.

  Depending on the type of return value, we can divide stored procedures into three categories: stored procedures that return recordsets, stored procedures that return numeric values ​​(also called scalar stored procedures), and behavioral stored procedures. As the name suggests, the execution result of a stored procedure that returns a recordset is a recordset. A typical example is retrieving records that meet one or more conditions from the database; a stored procedure that returns a value returns a value after execution, such as in the database. Execute a function or command with a return value; finally, a behavioral stored procedure is only used to implement a certain function of the database, and has no return value, such as update and delete operations in the database.

  The benefits of using stored procedures

  Compared to using SQL statements directly, calling stored procedures directly in an application has the following advantages:

  (1) Reduce network traffic. The network traffic of calling a stored procedure with a small number of rows may not be much different from calling SQL statements directly. However, if the stored procedure contains hundreds of rows of SQL statements, its performance is definitely better than calling SQL statements one by one. Much higher.

  (2) The execution speed is faster. There are two reasons: First, when the stored procedure is created, the database has already parsed and optimized it once. Secondly, once the stored procedure is executed, a copy of the stored procedure will be kept in memory, so that when the same stored procedure is executed next time, it can be called directly from the memory.

  (3) Stronger adaptability: Since the access of the stored procedure to the database is carried out through the stored procedure, the database developer can make any changes to the database without changing the interface of the stored procedure, and these changes will not affect the database. application is affected.

  (4) Distributed work: The coding work of the application program and the database can be carried out independently without suppressing each other.


Related notes above on msdn Reasons


to consider using a stored procedure

Maybe you've written T-SQL that uses the SqlCommand object in many places, but never considered a better place than incorporating it into your data access code. As the application adds functionality over time, it may contain some complex T-SQL procedural code inside it. Stored procedures provide an alternate place to encapsulate this code.

Most people probably already know about stored procedures, but for those who don't, a stored procedure is a set of T-SQL statements that are stored together as a single unit of code in a database. You can use input parameters to pass in runtime information and get back data as result sets or output parameters. Stored procedures will be compiled the first time they are run. This produces an execution plan - effectively a record of the steps Microsoft® SQL Server™ must take to get the result specified by T-SQL in the stored procedure. The execution plan is then cached in memory for later use. This improves the performance of the stored procedure because SQL Server does not need to re-analyze it to determine how to process the code, but simply refers to the cached plan. This cached plan is available until SQL Server is restarted, or until it overflows memory due to low usage.

performance

Cached execution plans have given stored procedures a performance advantage over queries. But with several recent versions of SQL Server, execution plans are cached for all T-SQL batches, whether they are in stored procedures or not. So performance based on this feature is no longer a selling point for stored procedures. Any T-SQL batch that uses static syntax and is committed frequently enough to prevent execution plans from overflowing memory will gain the same performance benefit. The "static" part is the key; any change, even something as trivial as adding a comment, will cause the plan to not be matched against the cached plan and thus will not be able to reuse the plan.

However, when stored procedures can be used to reduce network traffic, they can still provide performance benefits. You only need to send EXECUTE stored_proc_name statements over the network, rather than entire T-SQL routines, which can be widely used in complex operations. A well-designed stored procedure can simplify the many round-trips between the client and the server into a single call.

In addition, using stored procedures enables you to enhance the reuse of execution plans, which can improve performance by using remote procedure calls (RPCs) to process stored procedures on the server. When using StoredProcedure's SqlCommand.CommandType, the stored procedure is executed via RPC. The way RPC encapsulates parameters and calls server-side procedures allows the engine to easily find a matching execution plan and simply insert the updated parameter values.

When considering using stored procedures to improve performance, the final consideration is whether you want to take full advantage of T-SQL. Consider what to do with the data.


• Do
you want to use set-based operations, or perform other operations that are fully supported in T-SQL? Then stored procedures are an option, and inline queries can also be used.


Are you trying to perform line-based operations, or complex string manipulation? It might then be possible to reconsider doing this in T-SQL, excluding the use of stored procedures, at least until Yukon is released and Common Language Runtime (CLR) integration is available.



Maintainability and abstraction Another potential advantage

to consider is maintainability. Ideally, the database schema is never changed and business rules are never modified, but in a real-world environment, the situation is completely different. This being the case, instead of changing this information somewhere in the application code, what if the stored procedure could be modified to include data from the new X, Y, and Z tables (which were added to support the new sales activity) , maintenance may be easier for you. Changing this information in the stored procedure makes the update transparent to the application - you still return the same sales information, even if the internal implementation of the stored procedure has changed. Updating stored procedures generally requires less time and effort than changing, testing, and redeploying assemblies.

Also, by abstracting the implementation and keeping this code in a stored procedure, any application that needs to access the data can get consistent data. You don't need to maintain the same code in multiple places, so users get consistent information.

Another maintainability advantage of storing T-SQL in stored procedures is better versioning. You can version control scripts that create and modify stored procedures, just as you can version any other source code module. By using Microsoft Visual SourceSafe® or some other source control tool, you can easily revert to or reference an older version of the stored procedure.

One thing to note when using stored procedures to improve maintainability is that they do not prevent you from making all possible changes to your schema and rules. If the changes are large enough to require changes to the parameters of the input stored procedure, or to change the data returned by it, you still need to update the code in the assembly to add the parameters, update the GetValue() call, and so on.

Another issue to be aware of is that because stored procedures bind the application to SQL Server, using stored procedures to encapsulate business logic will limit the portability of the application. If application portability is important in your environment, encapsulating the business logic in a middle tier that is not RDBMS specific may be a better option.

Security The ultimate reason to

consider using stored procedures is that they can be used to enhance security.

As far as managing user access to information, they can provide access to specific data by granting users access to stored procedures rather than underlying tables. You can think of stored procedures as SQL Server views (if you are familiar with them), unless the stored procedure accepts user input to dynamically change the data displayed.

Stored procedures can also help you with code security issues. They prevent certain types of SQL insertion attacks - primarily those that use operators such as AND or OR to append commands to valid input parameter values. Stored procedures can also hide the implementation of business rules when an application is under attack. This is important for companies that treat such information as intellectual property.

In addition, using stored procedures allows you to specify the data type of stored procedure parameters using the SqlParameter class provided in ADO.NET. This provides an easy way to validate user-supplied value types as part of a defense-in-depth strategy. Parameters are just as useful in inline queries as they are in stored procedures in narrowing down the range of acceptable user input.

It's worth noting when using stored procedures for enhanced security that poor security or coding practices can still leave you open to attack. Creating and assigning SQL Server roles without care can result in people accessing data they shouldn't see. At the same time, if you think that using a stored procedure will prevent all SQL-insertion code attacks (eg, appending a Data Manipulation Language (DML) to an input parameter), the consequences will be the same.

Also, using parameters for data type validation is not foolproof, whether the T-SQL is in code or in a stored procedure. All user-supplied data (especially text data) should be subject to additional validation before being passed to the database.

Will stored procedures work for me?

Maybe it fits. Let's summarize their advantages:



Improve performance by reducing network traffic


Provide a single point of maintenance


Abstract business rules to ensure consistency and security


Enhance security by minimizing certain forms of attack


Support for execution plan reuse



If your environment allows you to take advantage of the benefits provided by stored procedures (as described above), using them is highly recommended. They provide a great tool for improving how data is handled in the environment. On the other hand, if your environment has factors such as portability, heavy use of non-T-SQL friendly processes, or unstable database schemas that diminish these benefits, you may want to consider other approaches.

Another consideration is the number of T-SQL professionals within the organization. Do you have enough T-SQL knowledge? Are you willing to learn? Or, do you have a DBA or the right person to help you write stored procedures? The more T-SQL knowledge you have, the better your stored procedures will be and the easier it will be to maintain them. For example, T-SQL is primarily used for set-based operations, not row-based operations. Relying on cursors (because they prompt you for datasets) will result in slower performance. If you don't know T-SQL very well, use this article as a learning opportunity. Wherever you use it, the knowledge in this article will improve your code.

Therefore, if you think stored procedures will add special effects to your application, please continue reading this article. We'll review some tools that simplify the use of stored procedures, and look at some best practices for creating stored procedures.




Considerations

If you 're starting to create stored procedures for use with your application, keep these tips in mind so that the two will function properly and work well together.

Using SET NOCOUNT ON

By default, stored procedures will return the number of rows affected by each statement in the procedure. If you do not need this information in your application (most applications do not), use the SET NOCOUNT ON statement in the stored procedure to stop this behavior. Depending on the number of row-affecting statements contained in the stored procedure, this removes one or more round-trips between the client and server. While this isn't a huge problem, it can negatively impact the performance of high-traffic applications.
create procedure test_MyStoredProc @param1 intasset nocount on

Do not use sp_ prefix

sp_ prefix is ​​reserved for system stored procedures. The database engine will always look for stored procedures with this prefix in the primary database first. This means that when the engine first checks the main database, and then checks the database where the stored procedure actually resides, it will take a longer time to complete the check process. And if there happens to be a system stored procedure with the same name, your procedure won't get processed at all. Use optional parameters sparingly Before using optional parameters

frequently, think carefully.

Performance can easily be impacted by performing extra work that is not needed depending on the set of parameters entered for an arbitrary specification of the execution. You can work around this by using conditional coding for every possible parameter combination, but this is time-consuming and increases the chance of error.

Use OUTPUT parameters when possible

You can achieve a slight speedup and save a small amount of processing power by using the OUTPUT parameter to return scalar data. In cases where your application needs to return a single value, try this approach instead of materializing the result set. The cursor can also be returned using the OUTPUT parameter under appropriate circumstances, but we'll cover the theoretical divergence between cursor processing and set-based processing in a follow-up article.

Provide return value

Use the return value of the stored procedure to return processing status information to the calling application. Across your development group, standardize on a set of return values ​​and their meanings, and use those values ​​consistently. This makes it easier to handle errors in the calling application and provides the end user with useful information about the problem. SQL Server will recompile the stored procedure when DDL is

used first, then DML is used to execute the DML statement after the data definition language (DDL) statement (where the DML will reference any object modified by the DDL).

This happens because, in order to create a plan for the DML, SQL Server needs to take into account the changes made to the object by the DDL. If you keep an eye on all the DDL at the beginning of the stored procedure, it only needs to be recompiled once. Mixing DDL and DML statements will force the stored procedure to recompile multiple times, which will negatively impact performance.

Always use comments

You may not always maintain this code. But others may want to learn about its use in the future. 'Nuff once said so.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326396534&siteId=291194637