0% found this document useful (0 votes)
47 views42 pages

Stored Procedures & User-Defined Functions: Hanoi University of Technology

This document discusses stored procedures and user-defined functions in SQL Server. It covers batch processing in SQL, T-SQL programming concepts like variables, cursors, control statements, and built-in functions. It also explains how to create, modify, delete and execute stored procedures. Finally, it provides an introduction to user-defined functions.

Uploaded by

trungt2k6
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views42 pages

Stored Procedures & User-Defined Functions: Hanoi University of Technology

This document discusses stored procedures and user-defined functions in SQL Server. It covers batch processing in SQL, T-SQL programming concepts like variables, cursors, control statements, and built-in functions. It also explains how to create, modify, delete and execute stored procedures. Finally, it provides an introduction to user-defined functions.

Uploaded by

trungt2k6
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 42

Stored Procedures &

User-Defined Functions

Vu Tuyet Trinh
[email protected]
Hanoi University of Technology

1
Introduction to SQL Batch Processing

Individual SQL
commands

Grouped to form a
batch
Batch

Compiled
as single
execution
plan

Microsoft
Example

Use Pubs
Select * from authors
Update authors
set phone= '890 451-7366‘
where au_lname= 'White'
Go

Microsoft
Outline

 Understanding the concepts of batch and batch


processing
 T-SQL Programming
 Define and assign variables
 Cursors for data retrieval
 Control statements
 Write SQL statements using SQL Server basic functions
 Use basic functions in a query
 Implementing Stored Procedures
 Implementing User-Defined Functions

Microsoft 4
Assigning values to variables

 SET statement
SET @local_variable name = value

 SELECT statement
SELECT @local_variable name = value

 Example SET @CUST=’FRANK’

SELECT CUSTOMERID,COMPANYNAME
FROM CUSTOMERS
WHERE CUSTOMERID = @CUST
Microsoft
Variables

SQL Server supports two types of variables in T-SQL


@@global_variable

@local_variable

Microsoft
List of Global variables

@@CONNECTIONS Number of connections made to the server


since it was last started.
@@CPU_BUSY Number of milliseconds the system has been
processing since SQL Server was started
@@CURSOR_ROWS Number of rows in the most recently opened
cursor.
@@ERROR Error number of the last T-SQL error
@@FETCH_STATUS 0 if the last fetch status was successful.
-1 if there was an error

Microsoft
List of Global variables (2)

@@IDENTITY Last inserted identity value


@@LANGUAGE Name of the language currently in use.
@@MAX_CONNECTIONS Maximum number of concurrent
connections that can be made.
@@ROWCOUNT Number of rows affected by most
recent SQL Statement
@@SERVERNAME Name of local server
@@SERVICENAME Name of the SQL Service on this
computer
@@TIMETICKS Number of microseconds per tick on
the current computer
@@TRANSCOUNT Number of transaction open on the
current connection
@@VERSION Version information of SQL Server

Microsoft
Cursors to Retrieve Data
 Allowing positioning at specific rows of the result set
 Retrieving one row or block of rows from the current
position in the result set
 Supporting data modifications to the rows at the current
position in the result set
 Supporting different levels of visibility for changes made
by other users to the data in the result set
 Providing access to the data in a result set for T-SQL
statements in scripts, stored procedures, and triggers

Microsoft
Cursor Implementations
 Transact-SQL Server Cursors
 Used in scripts, stored procedures, and triggers
 Implemented on the server

 API Server Cursors


 Implemented on the server but managed by API cursor
functions (OLE DB, ODBC, DB-Library)

 Client Cursors
 Entire result set is cached on client and all cursor
operations are performed against this cached set

Microsoft
Working with T-SQL Server Cursors
 Declare the cursor
 Populate the cursor
 Retrieve (fetch) the result set
 First, Next, Prior, Last, Absolute n, Relative n
 Optional: update or delete a row
 Close the cursor
 Free resources allocated to the cursor

Microsoft
Control Statements

Microsoft
Control Statements Contd…

Microsoft
BEGIN..END

A set of TSQL statements to be executed can be enclosed


in BEGIN..END.

Syntax:
BEGIN
{ statement | statement_block}
END

Microsoft
IF..ELSE

We can execute different


sets of SQL statements based on
specified conditions.

Syntax:
IF Boolean_expression

{ sql_statement | statement_block }

[ ELSE
{ sql_statement |
statement_block } ]

Microsoft
Example

Microsoft
WHILE construct

We can execute a SQL statement or a


block of statements based on some condition.

Syntax:
WHILE Boolean_expression
  { statement | statement_block }

    [ BREAK ]
    { statement | statement_block
}
    [ CONTINUE ]
Microsoft
Example
USE pubs
GO
WHILE (SELECT AVG(price) FROM titles) < $30
BEGIN
UPDATE titles
SET price = price * 2
SELECT MAX(price) FROM titles
IF (SELECT MAX(price) FROM titles) > $50
BREAK
ELSE
CONTINUE
END
PRINT 'Too much for the market to bear'

Microsoft
GOTO keyword

GOTO:
We can change the flow of execution to a specified location
(label). The statements after GOTO keyword are skipped and
the execution process continues at the specified label in the
GOTO statement.

Syntax:

GOTO label

Microsoft
RETURN

RETURN: We can use RETURN at any point to exit from a block,


procedure. Statements after the RETURN statement are not
executed.

Syntax:

RETURN [ integer_expression ]

Microsoft
CASE statement
 Allowing to return a value based on whether an
expression is true.
 Can be used wherever an expression is allowed.
 Syntax:
CASE expression
WHEN expression1 THEN expression1
[[WHEN expression2 THEN expression2] […]]
[ELSE expression]
END
 Example:

SELECT au_fname, au_lname,CASE state


WHEN 'OR' THEN 'Oregon'

END AS StateName FROM


authors
Microsoft
Multi column updates using CASE
UPDATE publishers
SET state =
CASE
    WHEN country <> "USA"
    THEN "--" Two or more
    ELSE state
END, columns can
city = be updated
CASE using one
    WHEN pub_id = "9999" command in
    THEN "LYON"
    ELSE city this manner
END
WHERE country <> "USA" OR
pub_id = "9999"

Microsoft
Math Functions

 AVG()
 MIN()
 MAX()
 SUM()
 COUNT()
 SQUARE()
 SQRT()
 ROUND()

Microsoft
String Functions

 ASCII()
 CHAR()
 UPPER()
 LOWER()
 LEN()
 LTRIM()
 RTRIM()
 LEFT()
 RIGHT()

Microsoft
Time Functions

 GETDATE()
 DATEPART(YY,getdate())
 DATEDIFF(X,Y,Z)
 DAY()
 MONTH()
 YEAR()

Microsoft
System Functions
 DB_ID([‘database_name’])
 DB_NAME([database_id])
 HOST_ID()
 HOST_NAME()
 ISNULL(expr,value)
 OBJECT_ID(‘obj_name’)
 OBJECT_NAME(object_id)
 SUSER_SID([‘login_name’])
 SUSER_ID([‘login_name’])
 SUSER_SNAME([server_user_id])
 SUSER_NAME([server_user_id])
 USER_ID([‘user_name’])
 USER_NAME([user_id])

Microsoft
Outline

 Understanding the concepts of batch and batch


processing
 T-SQL Programming
 Define and assign variables
 Cursors for data retrieval
 Control statements
 Write SQL statements using SQL Server basic functions
 Use basic functions in a query
 Implementing Stored Procedures
 Implementing User-Defined Functions

Microsoft 27
Stored Procedures

 Main ideas
 move the processing as close to the data as possible.
 Move into a batch that has been stored with a name so it can be
pre-compiled

 Advantages
 better performance
 higher productivity
 ease of use
 increased scalability.

Microsoft
Creating a Stored Procedure

USE SQLProject;
go
CREATE PROCEDURE GetSubjects
AS
SELECT SubjectCode, Name, Semester, CreditPoint
FROM dbo.Subject;
RETURN;
Microsoft
Modifying a Stored Procedure

ALTER PROCEDURE GetSubjects


AS
SELECT *
FROM dbo.Subject;
Microsoft
Deleting a Stored Procedure

DROP PROCEDURE dbo.GetSubjects

Microsoft
Executing a Stored Procedure

 Local stored procedures


Execute <Procedure_name>

 Remote stored procedures


Execute <server.database.schma.procedurename>
or
OpenQuery(linked server name,‘exec stored procedure’)

 Example
Execute dbo.GetSubjects

Microsoft
Outline

 Understanding the concepts of batch and batch


processing
 T-SQL Programming
 Define and assign variables
 Cursors for data retrieval
 Control statements
 Write SQL statements using SQL Server basic functions
 Use basic functions in a query
 Implementing Stored Procedures
 Implementing User-Defined Functions

Microsoft 33
User-Defined Function

 A function returning value


 Advantages:
 better performance, higher productivity, ease of use, increased
scalability for database application
 embed complex logic within a query.
 create new functions for complex expressions.
 Three distinct types
 Scalar functions that return a single value
 Updateable inline table functions similar to views
 Multi-statement table functions that build a result set with code

Microsoft
Creating a Scalar Function

Microsoft
Creating a Inline Table Function

Microsoft
Creating a Multi-statement table function

Microsoft
Modifying a Scalar Function

Microsoft
Modifying a Inline Table Functions

Microsoft
Modifying a Multi-statement Table Function

Microsoft
Summary

Microsoft 41
Microsoft

You might also like