8 T SQL Stored Procedures and Functions
8 T SQL Stored Procedures and Functions
and
User-Defined Functions
Fsoft Academy
Understand about
This isUSP, UDF
a sample andyouSQL
text that Code
can edit.
01 You can change font(size, color, name),
Practice in SQL Server.
or apply any desired formatting.
3.
3. Demo
• Block Comment:
• Ex: /*Multi-line comments here*/
• [1Person]
For Example:
SELECT * FROM [My Table]
WHERE [Order]=40
USE AdventureWorks2022;
GO
CASE input_expression
WHEN when_expression1 THEN result_expression1
WHEN when_expression2 THEN result_expression2
...
ELSE else_result_expression
END
GO
SELECT ProductNumber,
Category = CASE ProductLine
WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale' END,
Name
FROM Production.Product
ORDER BY ProductNumber;
BEGIN TRY
{ sql_statement | statement_block }
END TRY
BEGIN CATCH
[ { sql_statement | statement_block } ]
END CATCH
Syntax:
label :
GOTO label
Syntax
RETURN [ integer_expression ]
Stored Procedures
Because system procedures start with the prefix sp_, we recommend that
you do not use this prefix when naming user-defined procedures.
In this topic we will learn about User Stored Procedure.
END
GO
GO
CREATE PROCEDURE GetImmediateManager
@employeeID INT,
@managerID INT OUTPUT
AS
BEGIN
SELECT @managerID = ManagerID FROM HumanResources.Employee
WHERE EmployeeID = @employeeID
END
-- Call SP
DECLARE @ReturnValue INT
Stronger security: When calling a procedure over the network, only the call to
execute the procedure is visible. Therefore, malicious users cannot see table
and database object names, embed Transact-SQL statements of their own, or
search for critical data
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 27
Benefit of Using SP
Benefit of Using SP
Reuse of code:
• The code for any repetitious database operation is the perfect candidate for
encapsulation in procedure (for instance, UPDATE data on a table)
Improve Performance:
• Procedure is stored in cache area of memory when the stored procedure is first
executed so that it can be used repeatedly. SQL Server does not have to
recompile it every time the stored procedure is run.
Update a Procedure
ALTER PROC[EDURE] procedure_name
[ @parameter_name data_type] [= default] [OUTPUT]
[,...,n]
AS
SQL_statement(s)
Delete a Procedure
DROP PROC[EDURE] procedure_name
User-Defined Functions
!Important
Transact-SQL UDFs in queries can only be executed on a single thread (serial execution plan).
RETURNS return_data_type
[ AS ]
BEGIN
function_body
RETURN scalar_expression
END
Output: