Podcast
Questions and Answers
A ______ is a set of Transact-SQL statements compiled and stored as a single database object for repetitive use.
A ______ is a set of Transact-SQL statements compiled and stored as a single database object for repetitive use.
stored procedure
The ______ of a stored procedure defines its name, input and output parameters, and processing options.
The ______ of a stored procedure defines its name, input and output parameters, and processing options.
header
The ______ of a stored procedure contains the Transact-SQL statements executed at runtime.
The ______ of a stored procedure contains the Transact-SQL statements executed at runtime.
body
The ______ PROCEDURE
statement is used to create a new stored procedure.
The ______ PROCEDURE
statement is used to create a new stored procedure.
To modify an existing stored procedure, you can use the ______ PROCEDURE
statement.
To modify an existing stored procedure, you can use the ______ PROCEDURE
statement.
The ______ PROCEDURE
statement is used to remove a stored procedure from the database.
The ______ PROCEDURE
statement is used to remove a stored procedure from the database.
In SQL Server, the maximum length of a stored procedure identifier is ______ characters.
In SQL Server, the maximum length of a stored procedure identifier is ______ characters.
Stored procedures can contain up to ______ input and output parameters.
Stored procedures can contain up to ______ input and output parameters.
The maximum size of the body of a stored procedure is ______ MB.
The maximum size of the body of a stored procedure is ______ MB.
One of the functionalities of stored procedures is to implement ______ in the data tier.
One of the functionalities of stored procedures is to implement ______ in the data tier.
Stored procedures can be used to ______ access to data, enhancing database security.
Stored procedures can be used to ______ access to data, enhancing database security.
Using stored procedures can ______ the performance of the database system by reducing compile time.
Using stored procedures can ______ the performance of the database system by reducing compile time.
A stored procedure can return information to the caller using result sets, parameters, return values, and ______ .
A stored procedure can return information to the caller using result sets, parameters, return values, and ______ .
To obtain a result set from a stored procedure, use a Transact-SQL statement like ______ in the procedure's body.
To obtain a result set from a stored procedure, use a Transact-SQL statement like ______ in the procedure's body.
Multiple ______ can be returned from one stored procedure by including several SELECT
statements.
Multiple ______ can be returned from one stored procedure by including several SELECT
statements.
In a stored procedure, parameter identifiers must begin with the ______ sign (@).
In a stored procedure, parameter identifiers must begin with the ______ sign (@).
The ______ keyword is followed by the stored procedure's name when executing it.
The ______ keyword is followed by the stored procedure's name when executing it.
To use an OUTPUT
parameter within a stored procedure, you must ______ a variable to store the value.
To use an OUTPUT
parameter within a stored procedure, you must ______ a variable to store the value.
If a stored procedure does not explicitly set a return value, the server defaults to ______.
If a stored procedure does not explicitly set a return value, the server defaults to ______.
@@error
is a scalar function that contains an error number or ______ in case of success.
@@error
is a scalar function that contains an error number or ______ in case of success.
If a stored procedure statement has parameters, you must supply ______ for the parameters in your EXEC
statement.
If a stored procedure statement has parameters, you must supply ______ for the parameters in your EXEC
statement.
If a user fails to supply values for the parameters, the server reports an ______.
If a user fails to supply values for the parameters, the server reports an ______.
You can assign a ______ to a parameter in a stored procedure using an assignment (=).
You can assign a ______ to a parameter in a stored procedure using an assignment (=).
You do not have to follow parameter order if you pass parameters by ______.
You do not have to follow parameter order if you pass parameters by ______.
Passing parameters by position can be a little faster than passing parameters by ______.
Passing parameters by position can be a little faster than passing parameters by ______.
______-defined stored procedures are assembled by administrators or developers for later use.
______-defined stored procedures are assembled by administrators or developers for later use.
Before creating a stored procedure, it is good practice to check IF OBJECT_ID(...) IS NOT ______
to avoid errors.
Before creating a stored procedure, it is good practice to check IF OBJECT_ID(...) IS NOT ______
to avoid errors.
The ______ command marks the end of a batch in SQL Server.
The ______ command marks the end of a batch in SQL Server.
Inside the BEGIN...END
block, we use ______ INTO
to add new records to a table.
Inside the BEGIN...END
block, we use ______ INTO
to add new records to a table.
We use ______
within a stored procedure to modify existing records in a table.
We use ______
within a stored procedure to modify existing records in a table.
______ FROM
is used to remove records from a table within a stored procedure.
______ FROM
is used to remove records from a table within a stored procedure.
The ______
command is used to retrieve data from one or more tables in a database.
The ______
command is used to retrieve data from one or more tables in a database.
To check the success or failure of a query in SQL Server, you can use ______
which returns the number of rows affected.
To check the success or failure of a query in SQL Server, you can use ______
which returns the number of rows affected.
Inside a T-SQL ______
loop, a Boolean condition is checked every time the code within the loop is about to start.
Inside a T-SQL ______
loop, a Boolean condition is checked every time the code within the loop is about to start.
Loops are commonly used in conjunction with database cursors to process a set of data one row at a time.
Loops are commonly used in conjunction with database cursors to process a set of data one row at a time.
Sometimes you will wish to terminate a loop even when the condition part is true. This can be achieved using the ______
command.
Sometimes you will wish to terminate a loop even when the condition part is true. This can be achieved using the ______
command.
If you wish to terminate a single iteration of a loop, you can use the ______
command which immediately stops the current iteration and rechecks the loop's condition.
If you wish to terminate a single iteration of a loop, you can use the ______
command which immediately stops the current iteration and rechecks the loop's condition.
Loops can be ______ to provide more complex looping structures; in this arrangement, BREAK
and CONTINUE
commands affect only the loop that they appear within.
Loops can be ______ to provide more complex looping structures; in this arrangement, BREAK
and CONTINUE
commands affect only the loop that they appear within.
In MySQL, the ______
statement allows you to skip the entire code under it and start a new iteration.
In MySQL, the ______
statement allows you to skip the entire code under it and start a new iteration.
In MySQL, ______
is used to exit the flow control construct that has the given label.
In MySQL, ______
is used to exit the flow control construct that has the given label.
Flashcards
Stored Procedure
Stored Procedure
A pre-compiled set of T-SQL statements stored as a database object for repetitive use.
Stored Procedure Header
Stored Procedure Header
The stored procedure's name, input/output parameters, and processing options.
Stored Procedure Body
Stored Procedure Body
One or more T-SQL statements executed when the stored procedure runs.
CREATE PROCEDURE
CREATE PROCEDURE
Signup and view all the flashcards
ALTER PROCEDURE
ALTER PROCEDURE
Signup and view all the flashcards
DROP PROCEDURE
DROP PROCEDURE
Signup and view all the flashcards
EXEC or CALL
EXEC or CALL
Signup and view all the flashcards
IF OBJECT_ID(...) IS NOT NULL
IF OBJECT_ID(...) IS NOT NULL
Signup and view all the flashcards
GO
GO
Signup and view all the flashcards
Input Parameters
Input Parameters
Signup and view all the flashcards
Output Parameters
Output Parameters
Signup and view all the flashcards
INSERT INTO
INSERT INTO
Signup and view all the flashcards
UPDATE
UPDATE
Signup and view all the flashcards
DELETE
DELETE
Signup and view all the flashcards
SELECT
SELECT
Signup and view all the flashcards
@@ROWCOUNT
@@ROWCOUNT
Signup and view all the flashcards
WHILE Loop
WHILE Loop
Signup and view all the flashcards
LEAVE Statement
LEAVE Statement
Signup and view all the flashcards
CONTINUE/ITERATE
CONTINUE/ITERATE
Signup and view all the flashcards
Study Notes
- A stored procedure is a precompiled set of T-SQL statements stored in a database for repeated use, similar to subroutines or functions.
Anatomy of a Stored Procedure
- Header: Defines the procedure's name, parameters, and processing options, acting as an API or declaration.
- Body: Contains the T-SQL statements executed at runtime.
Creating Stored Procedures
- The basic syntax for creating stored procedures in SQL Server is as follows:
CREATE PROCEDURE procedure_name [{@parameter data_type} [= default] [OUTPUT] ] [,...n] AS sql_statement [...n]
- Example stored procedure to get equipment by make:
create procedure pr_equipment_get
@make varchar(50)
as
begin
select *
from tbl_equipment
where make = @make
end
- Stored procedures can be modified by either dropping and recreating them or using the
ALTER PROCEDURE
statement. - Using
ALTER PROCEDURE
is preferable to avoid undesirable effects on permissions and dependent objects. - Example of dropping and recreating a stored procedure in SQL Server:
Drop Procedure pr_EquipmentByEqTypeID_Get
go
Create Procedure pr_EquipmentByEqTypeID_Get
@intEqTypeId int
as
Select *
from tbl_equipment
where EqTypeId = @intEqTypeId
GO
- Example of creating or replacing a stored procedure in MySQL:
DELIMITER $$
CREATE OR REPLACE PROCEDURE pr_getEquipment(_id INT)
BEGIN
Select *
from tbl_equipment
where EqTypeId = _id;
END $$
DELIMITER ;
- Alternative method in SQL Server to drop a stored procedure if it exists:
IF object_id('pr_equipment_get') is not null
begin
drop PROCEDURE pr_equipment_get
end
Altering Stored Procedures
- The
ALTER PROCEDURE
statement modifies an existing stored procedure while preserving permissions and dependent objects. - Syntax for altering a stored procedure is similar to creating one, but uses the
ALTER
keyword. - Example of altering a stored procedure in SQL Server:
alter procedure pr_Equipment_Get
@make varchar(50)
as
Select *
from tbl_Equipment
where Make = @make
go
- Using
ALTER PROCEDURE
is better than dropping and recreating because it maintains the object identification number (id column) and references.
Limits of Stored Procedures
- Maximum identifier length (procedure name): 128 characters.
- Maximum number of input and output parameters: 2,100.
- Maximum size of the stored procedure body: 128MB.
Functionality of Stored Procedures
- Stored procedures can:
- Return information to the caller.
- Modify data in databases.
- Implement business logic in the data tier.
- Control access to data.
- Improve system performance.
- Reduce network traffic.
- Perform other actions (e.g., email, OS commands, SQL Server object management).
Ways to Receive Information from a Stored Procedure
- Returning result sets
- Using input and output parameters
- Using return values
- Global cursor
Returning Result Sets
- To return a result set, include a T-SQL statement that returns a result set (e.g., a
SELECT
statement). - A stored procedure can return multiple result sets using multiple
SELECT
statements. - Some client data-access methods may only access the first result set or report an error.
Using Input and Output Parameters
- Example: Stored procedure using input parameters to filter equipment by make and model:
Create procedure pr_EqIdByMakeModel_List
@make varchar(50),
@model varchar(50)
as
select EqId
from tbl_Equipment
where Make = @make and Model = @model
GO
- Execute a stored procedure with input parameters:
Execute pr_EqIdByMakeModel_List 'Toshiba', 'Portege 7020CT'
- Example using output parameter in SQL Server:
create procedure pr_Get_ID
@name varchar(1000), --parameter
@id int OUTPUT
as
begin
select @id = x_id from Table_1
where x_name = @name
end
- -in order to use our output parameter, we must declare a variable to store the value from OUTPUT variable
declare @IDX int -- declare our variable for storing value
exec pr_Get_ID 'MAMON', @IDX OUTPUT -- we use @IDX to store the value of our OUTPUT var
select @IDX -- return the value of our @IDX
- Example using output parameter in MySQL:
drop procedure pr_selTable2;
delimiter $$
create procedure pr_selTable2(_id int,OUT _nme varchar(50))
begin
select x_nme into _nme from tbl_X
where x_id = _id;
end $$
delimiter ;
call pr_selTable2 (1,@pangalan);
select @pangalan;
- Example using inout parameter in MySQL:
drop procedure pr_selTable3;
delimiter $$
create procedure pr_selTable3(_id int, INOUT _nme varchar(50))
begin
select x_nme into _nme from tbl_X
where x_id = _id;
set _nme = concat('hi',' ',_nme);
end $$
delimiter ;
call pr_selTable3 (2,@pangalan);
select @pangalan;
Using Return Values
- Stored procedures can return an integer value to the caller using the
RETURN
statement. - If no return value is specified, the default is zero (0).
- Example: SQL Server stored procedure returning EquipmentId:
Create Procedure pr_EqIdByMakeModel_List_3
@make varchar(50),
@model varchar(50)
as
Declare @intEqId int
Select @intEqId = EquipmentId
from tbl_equipment
where Make = @make and Model = @model
Return @intEqId
- Executing a stored procedure and accessing the returned value:
Declare @intEqId int
Execute @intEqId = pr_EqIdByMakeModel_List_3 'Toshiba', 'Portege 7020CT'
Select @intEqId 'Equipment Identifier'
- Example returning an error code using
@@error
:
Create Procedure pr_EqIdByMakeModel_List_5
@make varchar(50),
@model varchar(50),
@intEqId int output
as
select @intEqId = EqId
from tbl_equipment
where Make = @make and Model = @model
Return @@error
- Executing the above stored procedure:
Declare @intEqId int,
@intErrorCode int
Execute @intErrorCode = pr_EqIdByMakeModel_List_5 'Toshiba','Portege 7020CT', @intEqId
Select @intEqId result, @intErrorCode ErrorCode
- No equivalent code to Returning Values in MySQL
Default Values
- Parameters can have default values assigned using the
=
operator. - Example: Stored procedure with default parameter values:
create Procedure pr_EqIdByMakeModel_List_6
@make varchar(50) = '%', @model varchar(50) = '%'
as
Select *
from tbl_equipment
where Make Like @make and Model Like @model
- If a parameter is omitted during execution, the default value is used.
Passing Parameters by Name
- Parameters can be passed by name instead of position, improving code readability.
- Syntax:
@parameter_name = value
. - Example:
Execute ap_EqIdByMakeModel_List_6 @Model = 'T%'
- Passing parameters by name can make code more maintainable.
Types of Stored Procedures
- User-defined
- System
- Extended
- Temporary
- Global temporary
- Remote
- CLR
Stored Procedure Basics
CREATE PROCEDURE
: Used to create a stored procedure.EXEC
orCALL
: Executes a stored procedure.IF OBJECT_ID(...) IS NOT NULL
: Checks if a procedure already exists.DROP PROCEDURE
: Deletes an existing procedure.GO
: Marks the end of a batch (SQL Server only).
Parameters in Stored Procedures
- Input Parameters: Declared using
@parameter_name
(SQL Server) or_parameter_name
(MySQL). - Output Parameters: Defined with the
OUTPUT
keyword for returning values.
Data Manipulation (CRUD Operations)
INSERT INTO
: Adds new records.UPDATE
: Modifies existing records.DELETE
: Removes records.SELECT
: Retrieves data.- Example (SQL Server):
CREATE PROCEDURE pr_ManageEmployee
@opt INT, -- Operation type (1 = Insert, 2 = Update, etc.)
@nme VARCHAR(500),
@sal DECIMAL(12,4),
@bonus DECIMAL(12,4),
@id INT
AS
BEGIN
-- INSERT Operation
IF @opt = 1
BEGIN
INSERT INTO tbl_Employee (NAME_, SALARY, BONUS)
VALUES (@nme, @sal, @bonus);
END
-- UPDATE Operation
IF @opt = 2
BEGIN
UPDATE tbl_Employee
SET NAME_ = @nme, SALARY = @sal, BONUS = @bonus
WHERE ID = @id;
END
-- DELETE Operation
IF @opt = 3
BEGIN
DELETE FROM tbl_Employee
WHERE ID = @id;
END
-- SELECT Operation
IF @opt = 4
BEGIN
SELECT * FROM tbl_Employee;
END
END
Using @@ROWCOUNT (SQL Server)
@@ROWCOUNT
: Returns the number of rows affected by the previous statement, useful for checking success/failure of queries.- Example:
UPDATE tbl_Employee SET SALARY = @amt WHERE ID = @id;
IF @@ROWCOUNT > 0
PRINT 'Record updated successfully';
Using Loops and Temporary Tables and Table Variables in Stored Procedures
- Looping structures allow a single command, or a group of statements, to be executed repeatedly.
- When using the T-SQL WHILE loop, a Boolean condition is checked every time the code within the loop is about to start.
- If the condition is true, the loop is executed.
- If not, control passes to the statement following the loop.
- WHILE loops are commonly used with cursors to process a set of data one row at a time.
WHILE Loops
- (SQL Server)
WHILE condition statement
- (MySQL)
WHILE search_condition DO
statement_list
END WHILE
- Take note that the statement element can contain multiple commands if they appear between BEGIN and END commands.
- (SQL Server)
DECLARE @Iteration INT
SET @Iteration = 0
WHILE @Iteration< 10
BEGIN
PRINT @Iteration
SET @Iteration = @Iteration + 1
END
- Output:
0
1
2
3
4
5
6
7
8
9
- (MySQL)
delimiter $$
CREATE PROCEDURE dowhile()
BEGIN
DECLARE v1 INT ;
SET v1 = 0;
WHILE v1 10 THEN
LEAVE loop_label;
END IF;
SET x = x + 1;
IF (x mod 2) THEN
ITERATE loop_label;
ELSE
SET str = CONCAT(str,x,',');
END IF;
END LOOP;
SELECT str;
END$$
DELIMITER ;
Exiting a Loop Explicitly
- Sometimes you will wish to terminate a loop even when the condition part is true.
- This can be achieved using the BREAK command on SQL Server.
- This command specifies that the control should pass to the command immediately following the current loop.
- Example
DECLARE @ToSquare INT
DECLARE @Square INT
SET @ToSquare = 0
WHILE @ToSquare < 10
BEGIN
SET @ToSquare = @ToSquare + 1
SET @Square = @ToSquare * @ToSquare
IF @Square > 200
BREAK
PRINT @Square
END
- Output:
1
4
9
16
25
36
49
64
81
100
- In MySQL, LEAVE is used to exit the flow control construct that has the given label.
- If the label is for the outermost stored program block, LEAVE exits the program.
- In order to use LEAVE, we must place our loop or condition inside a label to tell our code where to exit.
- MYSQL Example
delimiter $$
CREATE PROCEDURE dowhile()
BEGIN
DECLARE v1 INT DEFAULT 5;
myLoop: WHILE v1 > 0 DO
SET v1 = v1 - 1;
if v1 < 3 then
leave myLoop;
end if;
END WHILE myLoop;
select v1;
END $$
delimiter ;
Restarting a Loop
- If you wish to terminate a single iteration of a loop you can use the CONTINUE command in SQL Server.
- This command immediately stops the current iteration and rechecks the loop's condition.
- If the condition is still true, the loop is restarted.
//SQL Server
DECLARE @ToSquare INT
DECLARE @Square INT
SET @ToSquare = 0
WHILE @ToSquare < 100
BEGIN
SET @ToSquare = @ToSquare + 1
SET @Square = @ToSquare * @ToSquare
IF @Square < 100
CONTINUE
IF @Square > 200
BREAK
PRINT @Square
END
- In MySQL, The ITERATE statement allows you to skip the entire code under it and start a new iteration.
- The ITERATE statement is similar to the continue statement in PHP, C/C++, Java, etc. ITERATE means “start the loop again.”.
- MYSQL Example
delimiter $$
CREATE PROCEDURE dowhile()
BEGIN
DECLARE v1 INT DEFAULT 0;
DECLARE str VARCHAR(255);
SET str = '';
myLoop: WHILE v1 10 then
leave myLoop;
end if;
SET v1 = v1 + 1;
IF (v1 mod 2) THEN
ITERATE myLoop;
ELSE
SET str = CONCAT(str,v1,',');
END IF;
END WHILE myLoop;
select str;
END $$
delimiter ;
Nesting
- Loops can be nested to provide more complex looping structures.
- When nesting loops, BREAK and CONTINUE commands affect only the loop that they appear within.
- i.e. when breaking out of an inner loop, control passes to the next statement after the inner loop, which will be within the outer loop.
//SQL Server
DECLARE @Val1 INT
DECLARE @Val2 INT
SET @Val1 = 1
WHILE @Val1< 3
BEGIN
SET @Val2 = 1
WHILE @Val2< 3
BEGIN
PRINT CONCAT(@Val1,' ',@Val2)
SET @Val2 = @Val2 + 1
END
SET @Val1 = @Val1 + 1
END
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.