Surviving Client/Server: Stored Procedures Part 1 by Steve Troxell

Surviving Client/Server: Stored Procedures Part 1 by Steve Troxell

Surviving Client/Server: Stored Procedures Part 1 by Steve Troxell tored procedures are a way of would simply be calls to invoke table, we get the amount of Sextracting SQL statements and those stored procedures. available credit for the customer. logic from an application and You generally pass information Listing 1 shows one way to embedding them within the between the application and the approach this problem using SQL database. Any application written stored procedure through parame- code embedded in the Delphi appli- in any language which has the ters in the procedure (not unlike a cation. Query1 and Query2 are TQuery facilities to execute SQL code can parameterized TQuery). Some back- components on the form. The SQL run these stored procedures and end servers, like Sybase, can statements we’re executing each manipulate their results. produce “implied results sets”, return a result set containing one This month, we’re going to meaning their stored procedures value, so we use Open to execute explore the pros and cons of stored can produce multi-row result sets them. After that, it’s a simple calcu- procedures in general and how to indistinguishable from a result set lation using the values returned to handle them in Delphi in particular. produced by a regular SQL query. determine the available credit. All Next month, we’ll go into greater Delphi provides the TStoredProc currency amounts in this example detail by exploring the various component to help you manage are assumed to be whole dollar types of stored procedures, how to your stored procedures. This com- amounts, so we use integer types. create them with Interbase and ponent has most of the functional- Listing 2 shows the definition of how to manipulate them from ity you’ll find in TQuery, which is not an Interbase stored procedure to Delphi. surprising since stored proce- do this same task. The stored While the concepts of stored dures are just server-based SQL procedure accepts an input pa- procedures are common across queries. In addition to TStoredProc, rameter, CustNo, defining the many back-end servers, the syntax you can also call stored proce- customer we are interested in. It and functionality varies widely dures through a TQuery with regular also returns two output parame- from vendor to vendor. Stored SQL commands. ters, CreditLimit and CreditAvail, procedures have not been a formal To illustrate how the use of returning the information we need. part of the SQL standard, so stored procedures affects the We use a local variable, CreditUsed, vendors have been free to imple- Delphi code you’ll write, we’ll take to temporarily hold the amount of ment them however they see fit. a simple database task and solve it credit used. You should view the material with SQL embedded within the Finally, Listing 3 shows the presented here as an overview to application and with a stored Delphi code that we use to call this stored procedures and consult procedure. stored procedure (this would your SQL server’s reference The task is this: You have a table replace the code shown in Listing manuals for specific information. called Customers from which you 1). StoredProc1 is a TStoredProc can look up a particular customer component on the form. What Is A Stored Procedure? by the CustomerNo field. Also in this OK, so the Delphi code is more Whereas a table is a database table is a CreditLimit field showing concise, but all we’ve done is shift object containing data, a stored the maximum amount of credit the load from one area to another. procedure is a database object which has been authorized for the Also, you could argue that it takes containing SQL code which usually customer. In addition, you have an more effort to develop the stored manipulates the data in one or Extensions table with a one-to- procedure version. So why go to more tables. It is really a server- many relationship to Customers the trouble of splitting the SQL based SQL query, but may also (linked through CustomerNo). This code out into a stored procedure? include flow control logic or data table contains one row for every computations. In this way, some credit extension (loan) given to the Encapsulated Logic portions of the system logic are customer. The BalanceDue column Since a calculation like this could separated from the Delphi applica- shows how much of the loan easily be needed at many points in tion and placed in the back-end remains to be paid (completely an application, or across multiple database. It’s not out of the paid loans have a BalanceDue of applications in an integrated sys- question that all SQL logic in a sys- zero). If we take the credit limit tem, we have encapsulated its logic tem could be located in stored found in the Customers table and at a single point in the database procedures and the only SQL state- subtract out all the outstanding itself. In so doing, we have removed ments remaining in the application balances found in the Extensions a business rule from the software 28 The Delphi Magazine Issue 6 function TForm1.GetCreditAvail(CustomerNum: LongInt): LongInt; site. Let’s say you developed a sys- begin tem containing the GetCreditInfo Result := 0; stored procedure and deployed it with Query1 do begin { Typically, the SQL code would be set through the property editor } SQL.Clear; for Customer A and Customer B, SQL.Add(’SELECT CreditLimit FROM Customers’); but Customer B wants to include SQL.Add(’ WHERE CustomerNo = :CustNo’); ParamByName(’CustNo’).AsInteger := CustomerNum; more factors in determining avail- Open; able credit than Customer A does. try with Query2 do begin All you have to do is modify SQL.Clear; Customer B’s stored procedure, SQL.Add(’SELECT SUM(BalanceDue) FROM Extensions’); none of the application software SQL.Add(’ WHERE CustomerNo = :CustNo’); ParamByName(’CustNo’).AsInteger := CustomerNum; needs to be modified. Open; It is this concept of encapsulated try { This check is needed in case there are no credit extensions on file for the customer } business rules in the database that if Query2.FieldByName(’Sum’).IsNull then is commonly referred to as ‘two- Result := Query1.FieldByName(’CreditLimit’).AsInteger else tier architecture’. The first tier is Result := Query1.FieldByName(’CreditLimit’).AsInteger - the client application which Query2.FieldByName(’Sum’).AsInteger; interacts with the user. The second finally Close; { Close Query2 } tier is the business rule logic at the end; server which interacts with the end; finally client application. Close; { Close Query1 } end; end; Improved Performance end; A second advantage of this stored procedure is that it executes more quickly than if the individual SELECT ➤ Listing 1 statements were sent as queries from the client. To understand why this is so, we must look at how an CREATE PROCEDURE GetCreditInfo(CustNo integer) RETURNS(CreditLimit integer, CreditAvail integer) SQL query is processed. AS When an SQL statement is re- DECLARE VARIABLE CreditUsed integer; BEGIN ceived from the client, the server SELECT CreditLimit FROM Customers parses the statement and validates WHERE CustomerNo = :CustNo it, checking its syntax and database INTO :CreditLimit; SELECT SUM(BalanceDue) FROM Extensions object references. It then formu- WHERE CustomerNo = :CustNo lates an execution plan for the INTO :CreditUsed; /* This check is needed in case there are no credit extensions on file for the customer */ query by deciding which, if any, IF (CreditUsed IS NULL) THEN CreditUsed = 0; indexes it will use to process the CreditAvail = CreditLimit - CreditUsed; END request. Some servers may at- tempt to reorganize the statement, compare the execution costs of ➤ Listing 2 various strategies and select the optimal approach. Finally the function TForm1.GetCreditAvail(CustomerNum: LongInt): LongInt; query is compiled and executed. begin However, with a stored proce- { Typically, this would be set through the property editor } with StoredProc1 do begin dure, all the steps of parsing, vali- StoredProcName := ’GetCreditInfo’; dating, optimizing, and compiling ParamByName(’CustNo’).AsInteger := CustomerNum; ExecProc; are performed when the procedure Result := ParamByName(’CreditAvail’).AsInteger; is created. When a client applica- end; tion executes a stored procedure, end; the server skips those steps since they have already been done and ➤ Listing 3 simply executes the pre-compiled SQL statements. This is the same and centralized it in the database, change the logic in the stored reason why using Prepare and where any application can use it. procedure and all affected applica- Unprepare with a TQuery improves By extracting business rules like tions will automatically respond to performance for repetitive para- this from the software, all applica- the new logic. meterized queries (see last tions can instantly respond to logic By the same token, encapsulated month): Prepare takes care of all changes without the need to business rules simplify the reus- the steps up through compilation. re-code, re-compile, and redistrib- ability of the software when in- But, those steps must still be per- ute EXEs or DLLs. We can simply stalled at more than one customer formed at least once at runtime. February 1996 The Delphi Magazine 29 With a stored procedure, those However, a stored procedure component is bound to a database steps are all handled in advance can read or modify a table inde- through the DatabaseName property, and are not needed at runtime. pendent of any permissions the you simply select the stored proce- Another way in which stored user might have. While at first dure from the drop-down list in the procedures can improve perform- glance this may seem to be a design StoredProcName property editor. ance is by reducing network traffic. flaw in the security of the database, With Interbase, Delphi automat- For example, if your application it’s actually an intentional feature ically populates the stored proce- needed to manipulate several rows to permit even tighter control over dure’s parameter names, types of data to arrive at a decision and data access.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    4 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us