What is a stored procedure?
Stored procedures are routines that reside in a database and encapsulate code.
What types of stored procedures does SQL Server permit?
What are the important features of a T-SQL stored procedure?
How many batches does a T-SQL stored procedure consist of?
A T-SQL stored procedure consists of a single batch of T-SQL code.
What T-SQL statements cannot be used in a T-SQL stored procedure?
Note that with a stored procedure the create, alter, and drop statements can be used. They can affect tables and indexes by using the CREATE, ALTER, and DROP statements.
How can a T-SQL stored procedure make a database more secure?
Rather than give the user access to database tables directly, you can grant permissions to a stored procedure. Stored procedures can also help prevent SQL injection attacks by parameterizing dynamic SQL.
How can a T-SQL stored procedure present a more versatile data access layer to users and applications?
The stored procedure allows the user to bypass complex logic to get desired results. Underlying physical structures of database tables may change and the stored procedure may be modified, but because the user sees the same procedure and parameters, the user does not need to know about the changes.
How can a T-SQL stored procedure help improve performance?
A T-SQL stored procedure helps improve performance by creating execution plans at the time the procedure is compiled that can be reused. By passing in parameters, you can reuse the cached plan of a stored procedure for many different parameter values, preventing the need to recompile the T-SQL code. Stored procedures can reduce network traffic too. If the application had to do all the work, intermediate results would have to be passed back to the application over the network. Similarly, if the application does all the work, it must send every T-SQL command to the SQL Server over the network.
What happens when you try to create a stored procedure and it already exists?
The CREATE command will fail.
If the stored procedure exists, it can be altered or dropped.
If a stored procedure that does not exist has an ALTER command issued, the ALTER command will fail.
Place a conditional DROP of the stored procedure before trying to create it.
IF OBJECT_ID(‘Sales.GetCustomerOrders’, ‘P’) IS NOT NULL DROP PROC Sales.GetCustomerOrders;
GO
How do you create stored procedure?
Use either CREATE PROCEDURE or use the abbreviation CREATE PROC.
CREATE PROC Sales.GetCustomerOrders
(
@custid AS INT,
@orderdatefrom AS DATETIME = ‘19000101’,
@numrows AS INT = 0 OUTPUT
)
AS BEGIN
RETURN (OUTPUT)
END
Parameters are optional. If there is no default initialization, the parameter is required.
In the previous code, @custid is a required parameter.
If a default initialization is provided, the parameter is optional.
If an optional parameter is not given a value when the procedure is called, the default value will be used in the rest of the procedure.
The OUTPUT keyword specifies a special parameter that returns values back to the caller.
Output parameters are always optional parameters.
The AS command is required after the list of parameters.
The code in a stored procedure is surrounded using a BEGIN/END block.
Though this is not required, using a BEGIN/END block can help clarify the code.
What does the NOCOUNT ON setting do?
The setting NOCOUNT ON inside a stored procedure removes messages like (3 row(s) affected) from being returned every time the procedure executes.
The NOCOUNT setting of ON or OFF stays with the stored procedure when it is created.
Placing a SET NOCOUNT ON at the beginning of every stored procedure prevents the procedure from returning messages to the client.
It can also improve the performance of frequently executed stored procedures because there is less network communication required when the message is not returned from the client.
What does the RETURN statement do in the context of a stored procedure?
A stored procedure normally ends when the T-SQL batch ends, but you can cause the procedure to exit at any point by using the RETURN command.
More than one return command can be used in a procedure.
RETURN stops the execution of the procedure and returns control back to the caller.
Statements after the RETURN statement are not executed.
RETURN by itself causes SQL Server to send a status code back to the caller.
The statuses are 0 for successful and a negative number if there is an error.
However, the error numbers are not reliable - so you should not use them.
Use the SQL Server error numbers from @@ERROR or from ERROR_NUMBER() in a CATCH block instead.
To send your own return codes back to the caller, inserti an integer value after the RETURN statement.
However, if you want to send information back to the caller, it is considered best practice to use an OUTPUT parameter.
How do you execute a stored procedure?
Use the EXECUTE statement (or EXEC for short).
If a stored procedure does not have any input parameters, use EXEC followed by the stored procedure name, EXEC sp_configure
NOTE: System stored procedures in the master database can be executed from any database. If the execution of a stored procedure is the first statement in a batch of T-SQL code or the only statement selected in a query window, you do not need the EXEC statement.
If a stored procedure is the second or later statement, you must precede it with EXEC or EXECUTE.
It is a best practice to always include the EXEC command when calling a stored procedure. That will avoid getting unexpected errors.
How do you pass parameters to a stored procedure when it is invoked?
EXEC Sales.GetCustomerOrders 37, ‘20070401’, ‘20070701’;
or
EXEC Sales.GetCustomerOrders @custid = 37, @orderdatefrom = ‘20070401’, @orderdateto = ‘20070701’
When you pass the parameter values by using the parameter names, you can put the named parameters in any order.
However, when you pass the parameter values by position, you must use the exact position of the parameters as defined in the CREATE PROCEDURE statement.
It is a best practice to name the parameters when you call stored procedures. If you pass parameters by name and the parameter order changes in the stored procedure, your call of the procedure will still work.
How do you use output parameters in a stored procedure?
Add the keyword OUTPUT (which can be abbreviated as OUT) after the parameter when you declare it in the CREATE PROC statement.
CREATE PROC Sales.GetCustomerOrders …
@numrows AS INT = 0 OUTPUT
AS …
To retrieve data from the output parameter, you must also use the keyword OUTPUT when you call the stored procedure and you must provide a variable to capture the value when it comes back.
(If you don’t have the OUTPUT keyword in the procedure value, no value will be returned in the variable)
DECLARE @rowsreturned INT;
EXEC Sales.GetCustomerOrders
@custid =37,
@orderdatefrom = ‘20070401’,
@orderdateto = ‘20070701’,
@numrows = @rowsreturned OUTPUT;
What are the IF/ELSE statements?
The IF/ELSE construct gives you the ability to conditionally execute code.
Enter an expression after the IF keyword and if the expression evaluates to TRUE, the statement or block of statements after the IF statement will be executed.
The optional ELSE is used to add a different statement or block of statements to be executed if the expression evaluates to false.
IF @var1 = @var2 PRINT ‘The variables are equal.’
ELSE PRINT ‘The variables are not equal.’
When the IF/ELSE statements are used without the BEGIN/END blocks, they each only deal with one statement.
What is the WHILE statement?
With the WHILE construct, you can create loops inside T-SQL in order to execute a statement block as long as a condition continues to evaluate to true. You can use the WHILE construct in cursors or you can use it by itself. The keyword WHILE is followed by a condition that evaluates to either true or false. If the condition evaluates to true when it’s first tested, the control of execution enters the loop, finishes the commands in side the loop the first time, and then tests the condition again. Each time the loop is repeated, the WHILE condition is retested. As soon as the loop ends and execution control passes to the next statement following the WHILE loop. WHILE @count SET @count += 1 END When you create a WHILE loop, it is critical to ensure that something happens in the loop that will eventually make it terminate. Always check the body of the WHILE loop to make sure that the counter is incremented or a value changes so that the loop will terminate. Inside the WHILE loop, use a BREAK statement to end the loop immediately and a CONTINUE statement to cause execution to jump back to the beginning of the loop.
What is the WAITFOR command?
The WAITFOR command does not change control flow or cause branching, it causes the execution of statements to pause for a specified period of time.
WAITFOR has three options: WAITFOR DELAY, WAITFOR TIME, and WAITFOR RECEIVE (which is used only with Service Broker).
WAITFOR DELAY causes the execution to delay for a requested duration.
Pauses the code execution for 20 seconds: WAITFOR DELAY ‘00:00:20’;
WAITFOR TIME on the other hand, pauses the execution to wait for a specific time.
Waits until 11:45: WAITFOR TIME ‘23:46:00’;
What is the GOTO construct?
With the GOTO construct, you can cause your code to jump to a defined T-SQL label. All the intervening T-SQL code is skipped when the jump occurs. For example, in the following code, the second PRINT statement is skipped:
PRINT ‘First PRINT statement’;
GOTO MyLabel;
PRINT ‘Second PRINT statement’;
MyLable: PRINT ‘End’;
It is not recommended to use the GOTO statement because it can lead to code that is complex and convoluted.
Can a stored procedure return multiple result sets back to a client?
Yes.
Can you call a stored procedure from another stored procedure?
Yes, but you need to observe the following when calling other procedures:
If you create a temp table in one stored procedure, call it Proc1 - that temporary table is visible to all other stored procedures called from Proc1. However, that temporary table is not visible to any procedures that calls Proc 1. Also, variables declared in Proc1 and Proc1’s parameters are not visible to any of the procedures called by Proc1.
Can a stored procedure span multiple batches of T-SQL code?
No. A stored procedure can only contain one batch of T-SQL code.
Can an OUTPUT parameter both pass data into a stored procedure and retrieve information back from it?
Yes.
An OUTPUT parameter can both pass data into a stored procedure and retrieve information back from it, by using an output parameter.
What is a trigger?
A trigger is a special kind of stored procedure that is associated with selected DML events on a table or a view.
A trigger is not explicitly executed.
Rather, a trigger is fired when a DML event occurs that the trigger is associated with, such as INSERT, UPDATE, or DELETE event.
Whenever the event takes place, the trigger fires and the trigger’s code runs.