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
Cursors
11. Navigate to the ApressFinancial database,
expand the Programmability node, and right-click
Stored Procedures. From the pop-up menu, select
New Stored Procedure. This opens a Query Editor
pane with code from a basic stored procedure
template
12. When you execute the preceding code, providing
you have made no typing
mistakes, you should see the following output:
13.
14. • 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.
15.
16.
17. The first section of code checks
whether the stored procedure
exists. If it does, then at execution,
it is deleted by using the
DROP PROCEDURE statement.
18. The final section of the stored procedure returns a value from a system global
variable, @@ROWCOUNT. this system variable returns the number of rows returned in the
previous T-SQL statement. From this, the calling code can tell whether there have been
problems and can then decide whether to ignore any values in the OUTPUT parameter.
19. The first part of this section defines the
variables that hold the output values and
the return value. Then the code moves
to the EXECUTE section of code. When
a value is returned from a stored
procedure, it is set on the left-hand side
of the stored procedure call and is not a
parameter value. Then the stored
procedure is defined with the three
parameters. Note that each output
parameter has to have the OUTPUT
keyword after it. The final section of the
code is a SELECT statement displaying
the values returned and the output
parameter.
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.
20. 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 the
following code.
21.
22.
23. You may want to test a condition and, if it returns a particular result, BREAK the
loop and exit the WHILE block. The other option that can be used is the
CONTINUE statement. This moves processing straight to the WHILE statement
again and will stop any execution of code that is defined after it.
24. 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 code
back to the WHILE statement via the CONTINUE statement. Either of
these actions will mean that the second SELECT will not execute.
25.
26.
27.
28.
29. First is the CREATE PROCEDURE statement that you enter in an empty Query Editor pane, and
then you name the procedure with the three input parameters
30.
31. You can now create the stored procedure and test it. The example is going to check whether
customer ID 1 has had a positive or negative movement on his or her cash balance in the month of
August 2011. The code to find this out follows. First of all, you insert some
TransactionDetails.Transactions records to test it out. You also prefix the stored procedure
with an EXEC(UTE) statement, as this is part of a batch of statements
32.
33. The first security consideration
is to define who can create,
modify, or drop objects in your
database. Objects are tables,
views, stored procedures, and
so on as well as database users,
roles, and so on.
The next security consideration is data access and how this should be implemented. There are
two 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 stored
procedures or views. This means that there is no direct table access. A stored procedure should
be written for each action on each table or tables.
34.
35. • 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.
36.
37. • 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.
39. Searching for a user or a
role
The roles and users that can be chosen
40. 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.
41. The permission is now applied, and you can check this by switching to MSmith
and executing the following code:
EXEC CustomerDetails.apf_CustMovement 1,'1 Aug 2011','31 Aug 2011'
You can achieve the same permissions via T-SQL using the GRANT statement.
GRANT EXECUTE ON CustomerDetails.apf_CustBalances
TO [FAT-BELLY-SONYApress_Product_Controllers]
42. Find the ClearedBalance column and click Deny. For all other columns in the list, you need to click
the GRANT column. This will then deny this principal from accessing the ClearedBalance column
but 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.
43.
44. Every parameter can be modified within the function as part of the function’s
execution, unless you place the keyword READONLY after the data type when
defining the function. As with stored procedures, it is possible to call a function
and omit specifying one or more of that function’s parameters. Any parameters that you
omit must have been defined with default values. In that case, you can call the function
with the keyword DEFAULT in the location that such a parameter is expected.
45.
46. 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 value
demonstrates how to specify default parameter values when invoking a function.
51. Create the temporary table.
populate the temporary table with information from the ShareDetails.Shares and the
ShareDetails.SharePrices tables.
The final part is to prove that there are data in the table.
52. Create the temporary table. taking note of the double hash marks
When you execute the code, you should see the same results as you did with the first query
Move to a new Query Editor, ensuring that you leave the previous Query Editor pane still open. Then
enter the following SELECT statement:
53.
54. 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.
55.
56.
57.
58.
59. Next step is to declare the cursor name and the SELECT statement to return the rows of
data for the cursor. The aim of the cursor is to return rows where there is a monthly amount
to collect from a customer, and the last amount collected was in March.