Stored procedures


Published on

Describe what a stored procedure is
Explain the advantages of a stored procedure over a view
Cover the basic syntax for creating a stored procedure
Show how to set values within variables
Control the flow through a stored procedure
Look at the differences between a function and a stored procedure
Cover the basic syntax for creating a T-SQL user-defined function
Temporary Tables

Published in: Education, Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Stored procedures

  1. 1. Navigate to the ApressFinancial database,expand the Programmability node, and right-clickStored Procedures. From the pop-up menu, selectNew Stored Procedure. This opens a Query Editorpane with code from a basic stored proceduretemplate
  2. 2. When you execute the preceding code, providingyou have made no typingmistakes, you should see the following output:
  3. 3. • Different Methods of Execution • There are two different methods of executing a stored procedure. The first is to just call the stored procedure, as you saw in the preceding example. The second method is to use the EXEC(UTE) command. Both have the end result of invoking the stored procedure, but which is better for you to use depends on the particular situation.
  4. 4. The first section of code checkswhether the stored procedureexists. If it does, then at execution,it is deleted by using theDROP PROCEDURE statement.
  5. 5. The final section of the stored procedure returns a value from a system globalvariable, @@ROWCOUNT. this system variable returns the number of rows returned in theprevious T-SQL statement. From this, the calling code can tell whether there have beenproblems and can then decide whether to ignore any values in the OUTPUT parameter.
  6. 6. The first part of this section defines thevariables that hold the output values andthe return value. Then the code movesto the EXECUTE section of code. Whena value is returned from a storedprocedure, it is set on the left-hand sideof the stored procedure call and is not aparameter value. Then the storedprocedure is defined with the threeparameters. Note that each outputparameter has to have the OUTPUTkeyword after it. The final section of thecode is a SELECT statement displayingthe values returned and the outputparameter. If you run the stored procedure with a customer number that is not in the database, you will see NULL values in the two output parameters and a return value of 0.
  7. 7. From an empty Query Editor, create the following stored procedure. Notice that there are two SELECT statements. Once you have entered the code, execute it so that the stored procedure is created.Test the stored procedure by entering and executing thefollowing code.
  8. 8. You may want to test a condition and, if it returns a particular result, BREAK theloop and exit the WHILE block. The other option that can be used is theCONTINUE statement. This moves processing straight to the WHILE statementagain and will stop any execution of code that is defined after it.
  9. 9. In this example, the first SELECT will show the values of the variables,but the IF test will either stop the loop via BREAK or move the codeback to the WHILE statement via the CONTINUE statement. Either ofthese actions will mean that the second SELECT will not execute.
  10. 10. First is the CREATE PROCEDURE statement that you enter in an empty Query Editor pane, andthen you name the procedure with the three input parameters
  11. 11. You can now create the stored procedure and test it. The example is going to check whethercustomer ID 1 has had a positive or negative movement on his or her cash balance in the month ofAugust 2011. The code to find this out follows. First of all, you insert someTransactionDetails.Transactions records to test it out. You also prefix the stored procedurewith an EXEC(UTE) statement, as this is part of a batch of statements
  12. 12. The first security considerationis to define who can create,modify, or drop objects in yourdatabase. Objects are tables,views, stored procedures, andso on as well as database users,roles, and so on.The next security consideration is data access and how this should be implemented. There aretwo schools of thought on how to achieve this. The first school of thought is that all data access,regardless of whether it is to insert, update, delete, or view data, should be done through storedprocedures or views. This means that there is no direct table access. A stored procedure shouldbe written for each action on each table or tables.
  13. 13. • PRIVILEGES: This keyword is optional and exists due to ISO compliance and is nonfunctional on permissions.• Permission: The permission you will be granting; permissions include EXECUTE, SELECT, INSERT, DELETE, UPDATE.• Column: The name or list of the column(s) that you will be granting privileges on; the list has to be surrounded by parentheses.• ON securable: Optional; the securable object you are granting privileges on; this could be the table, stored procedure, or view.• TO principal: The security principal that is receiving the privilege; this could be a database user or an application role.• WITH GRANT OPTION: Optional; you can allow the principal defined in the statement to grant this permission to other principals. This is something you need to take care with as you could allow that principal to grant the privilege to another principal that you have had no control over.• AS principal: Optional; it is possible to grant an object permission to a specific principal, but that principal derives its permissions from a different principal.
  14. 14. • GRANT OPTION FOR: If you have granted permission and included the WITH GRANT option, you can revoke the ability to pass on privileges.• PRIVILEGES: The keyword is included for ISO compliance and has no effect on permissions.• Permission: The permission you wish to revoke• ON securable: The securable object that you are revoking the permission on• TO | FROM principal: The security principal that you are revoking the privilege from• CASCADE: If you granted permission on an object to a principal using the WITH GRANT option, and this principal granted permission to another principal and soon, then by using the CASCADE option, the privilege will be revoked for the principal mentioned plus all the principals down the chain.• AS principal: Optional; it works for REVOKE much as it does for GRANT, but revokes instead of grants.
  15. 15. Permissions page for thestored procedure
  16. 16. Searching for a user or aroleThe roles and users that can be chosen
  17. 17. The user added and the potential permissions that can be granted• Alter: Selecting this option would allow the principal to alter the code.• Control: Similar to owning a securable/object, by granting this the principal would have similar permissions. However, you can then deny specific actions.• Take ownership: At present this object is owned by the account that created it. It is possible to take ownership of the object. This option is more likely to be set on schemas than stored procedures.• View definition: Allows the user to see the metadata of the object; in this case, you would be able to see the contents of the stored procedure.
  18. 18. The permission is now applied, and you can check this by switching to MSmithand executing the following code: EXEC CustomerDetails.apf_CustMovement 1,1 Aug 2011,31 Aug 2011You can achieve the same permissions via T-SQL using the GRANT statement. GRANT EXECUTE ON CustomerDetails.apf_CustBalances TO [FAT-BELLY-SONYApress_Product_Controllers]
  19. 19. Find the ClearedBalance column and click Deny. For all other columns in the list, you need to clickthe GRANT column. This will then deny this principal from accessing the ClearedBalance columnbut allow it to SELECT from all the others. Click OK, which will return you to the Permissions page.You can click OK, or click Cancel and then execute the following T-SQL statement instead.
  20. 20. Every parameter can be modified within the function as part of the function’sexecution, unless you place the keyword READONLY after the data type whendefining the function. As with stored procedures, it is possible to call a functionand omit specifying one or more of that function’s parameters. Any parameters that youomit must have been defined with default values. In that case, you can call the functionwith the keyword DEFAULT in the location that such a parameter is expected.
  21. 21. Include the following EXECUTE AS clause to specify that the function will execute in the same security context as the calling code. This security context is determined by the AS CALLER clause.You can now test the function by executing it against a set of values. The interest rate default valuedemonstrates how to specify default parameter values when invoking a function.
  22. 22. Using the FunctionAs the result is a table, it can be used like one.
  23. 23. Create the temporary table.populate the temporary table with information from the ShareDetails.Shares and theShareDetails.SharePrices tables.The final part is to prove that there are data in the table.
  24. 24. Create the temporary table. taking note of the double hash marksWhen you execute the code, you should see the same results as you did with the first queryMove to a new Query Editor, ensuring that you leave the previous Query Editor pane still open. Thenenter the following SELECT statement:
  25. 25. The options are as follows:• cursor_name: The name of the cursor that will then be referenced with the other cursor statements• LOCAL|GLOBAL: Similar to temporary tables, there are two scopes for cursors, the local connection or the global connection. Local is the default.• FORWARD ONLY|SCROLL: Forward indicates only that you are scrolling a row at a time from the start of the cursor to the end. This is the default. The SCROLL option indicates that you can move forward, backward, first, last, and to a specific position.
  26. 26. Next step is to declare the cursor name and the SELECT statement to return the rows ofdata for the cursor. The aim of the cursor is to return rows where there is a monthly amountto collect from a customer, and the last amount collected was in March.
  27. 27.