sql server tsql [read-only] - csuohio.educis.csuohio.edu/~sschung/ist331/sql_server_tsql.pdf ·...
TRANSCRIPT
1
SQL Server
Server Side Programming using T-SQL
Great Bison – Altamira Cave 17000 BC
2
June 18, 2007 –Worldwide relational database management systems (RDBMS) total software revenue totaled $15.2 billion in 2006, a 14.2 percent increase from 2005 revenue of $13.3 billion.
Microsoft SQL Server.
Worldwide Database Market
http://www.gartner.com/it/page.jsp?id=507466Additional information is available in the Gartner report “Market Share: Relational Database Management Systems by Operating System, Worldwide, 2006.” The report is available on Gartner’s Web site at http://www.gartner.com/DisplayDocument?ref=g_search&id=507295&subref=simplesearch.
Exxon posts biggest annual profit on record for a U.S. corporation Record oil prices help the world's largest public oil company earn $39.5 billion in 2006.
CNNmoney.com http://money.cnn.com/2007/02/01/news/companies/exxon/index.htm
3
Microsoft SQL Server.
Worldwide Database Market
Company 20062006
Market Share (%)
20052005
Market Share (%)
2005-2006 Growth (%)
Oracle 7,168.0 47.1 6,238.2 46.8 14.9
IBM 3,204.1 21.1 2,945.7 22.1 8.8
Microsoft 2,654.4 17.4 2,073.2 15.6 28.0
Teradata 494.2 3.2 467.6 3.5 5.7
Sybase 486.7 3.2 449.9 3.4 8.2
Other Vendors 1,206.3 7.9 1,149.0 8.6 5.0
Total 15,213.7 100.0 13,323.5 100.0 14.2
Additional information is available in the Gartner report “Market Share: Relational Database Management Systems by Operating System, Worldwide, 2006.” The report is available on Gartner’s Web site at http://www.gartner.com/DisplayDocument?ref=g_search&id=507295&subref=simplesearch.
4
Microsoft SQL Server.
2006 Worldwide Database Market
Additional information is available in the Gartner report “Market Share: Relational Database Management Systems by Operating System, Worldwide, 2006.” The report is available on Gartner’s Web site at http://www.gartner.com/DisplayDocument?ref=g_search&id=507295&subref=simplesearch.
5
Microsoft SQL Server.
2005 Global Database Market
Takeb from: http://www.idc.com/ Visited on 22-Oct-2006
Top Five (% market)
Oracle 44.6
IBM 21.4
Microsoft 16.8
Sybase 3.5
NCR-Teradata 2.9
Others 10.8
$14.6 Billion Dollars
May 24, 2006 – The worldwide market for relational database management systems (RDBMS) grew by 9.4% to $14.6 billion in 2005, according to preliminary figures released by IDC.
These numbers reflect steady growth for the RDBMS software market, indicating a continued increase in the deployment of relational databases.
6
Microsoft SQL Server.
SQL Server 2005
Microsoft-SQL Server 2005 is a relational database management system (RDBMS) from Microsoft that's designed for the enterpriseenvironment.
SQL Server runs on T-SQL (Transact -SQL), a set of programming extensions from Sybase and Microsoft that enhances the capabilities of standard SQL.
According to Microsoft the SQL Server 2005 provides improved flexibility, scalability, reliability, and security to database applications, and makes them easier to create and deploy, it also includes more administrative support.
7
Excerpts taken from (reliable ? accurate ? but always entertaining) www.wikipedia.com on Nov-2006
Sybase Inc. (NYSE: SY) is a software company specializing in relational database management systems and database-related products. "Sybase" is also commonly used to refer to Adaptive Server Enterprise, the company's flagship relational database system. Sybase's original architects were Dr. Robert Epstein and Tom Haggin who both had worked at Briton-Lee and the University of California, Berkeley Department of Computer Sciences (1984).
The pioneering "University Ingres" relational database system, developed at UC Berkeley, led to Briton-Lee, Sybase, Ingres (Computer Associates) Informix (IBM) and NonStop SQL (Tandem), as well as the majority of other SQL systems currently in use.
Sybase became the number 2 database system behind Oracle, after making a deal with Microsoft to share the source code for Microsoft to remarket on the OS/2 platform as "SQL Server". At the time, Sybase called the database server "Sybase SQL Server".
Microsoft SQL Server.
SQL Server 2005 and SYBASE
8
CONT. Excerpts taken from … www.wikipedia.com on Nov-2006
Until version 4.9, Sybase and Microsoft SQL server were virtually identical. Due to disagreements between the two companies over revenue sharing (or lack thereof), Sybase and Microsoft decided to split the code-lines and went their own way, although the shared heritage is very evident in the Transact-SQL (TSQL) procedural language as well as the basic process architecture. The big difference is that Sybase has a Unix heritage, while Microsoft sprung from that original Unix architecture and was adapted and optimized only for the Microsoft Windows NT operating system. Sybase continues to offer versions for Windows, several flavors of Unix, and for Linux.
Sybase suffered a major downturn in fortune in the latter half of the 1990s when Informix started outselling it by a wide margin. Today Informix is no longer an independent company (having been bought by IBM). Today Sybase is well behind its major competitors in the enterprise database market, with 3% market share (InformationWeek March 05).
Sybase has recently returned to profitability under the management of John Chen, and continues to reinvent itself with a new 'Unwired Enterprise' strategy. The 'Unwired Enterprise' vision is about allowing companies to deliver data to mobile devices in the field as well as traditional desktops, and combines technology from Sybase's existing data management products with its new mobility products. Sybase has expanded into the mobile and wireless space through buyouts of smaller networking and wireless companies. Through its mobility subsidiary, launched in 2000, iAnywhere Solutions, Sybase has become the leader of the mobile database market with SQL Anywhere.
Microsoft SQL Server.
SQL Server 2005 and SYBASE
9
Microsoft SQL Server.
SQL Server 2005 Technologies
10
Microsoft SQL Server.
SQL Server 2005 Technologies
SQL Server Database Engine. The Database Engine is the core service for storing, processing, and securing data in either a relational (tabular) format or as XML documents.
SQL Server Analysis Services. Analysis Services delivers online analytical processing (OLAP) and data mining functionality for business intelligence applications.
SQL Server Integration Services (SSIS). Integration Services is an enterprise data transformation and data integration solution that you can use to extract, transform, and consolidate data from disparate sources and move it to single or multiple destinations.
SQL Server Replication. Replication is a set of technologies for copying and distributing data and database objects from one database to another and then synchronizing between databases to maintain consistency.
11
Microsoft SQL Server.
SQL Server 2005 Technologies
SQL Server Reporting Services. Reporting Services is a server-based reporting platform that you can use to create and manage tabular, matrix, graphical, and free-form reports that contain data from relational and multidimensional data sources. The reports that you create can be viewed and managed over a Web-based connection.
SQL Server Notification Services. Notification Services is the platform for developing and deploying applications that generate and send notifications to thousands or millions of subscribers, and deliver them to a wide variety of devices.
SQL Server Service Broker. Service Broker also provides integration, queueing, and a message-based communication platform that can be used to link disparate application components into a functioning whole.
Full-Text Search. SQL Server contains the functionality to issue full-text queries against plain character-based data in SQL Server tables.
12
Microsoft SQL Server.
SQL Server Management Studio
SQL Server Management Studio is a suite of administrative tools for managing the components belonging to SQL Server. Including
• Code Editor is a script editor for writing and editing scripts. There are four versions: the SQL Query Editor, MDX Query Editor, XML Query Editor, and SQL Mobile Query Editor.
• Object Explorer for locating, modifying, scripting or running objects belonging to instances of SQL Server.
• Template Explorer for locating and scripting templates.
• Solution Explorer for organizing and storing related scripts as parts of a project.
• Properties Window for displaying the current properties of selected objects.
13
Microsoft SQL Server.
SQL Server Management Studio
14
Microsoft SQL Server.
SQL Server Management Studio
15
Microsoft SQL Server.
SQL Server Management Studio
16
Microsoft SQL Server.
SQL Server Management Studio
Exploring Database
1. Connect to the COMPANY database
2. Explore the contents of selected database
17
Microsoft SQL Server.
SQL Server Management Studio
Table Structure
1. Select a table.
2. Right-click.
3. Select MODIFY option to see/change structure of a table.
18
Microsoft SQL Server.
SQL Server Management Studio
Multiple Databases
1. Select another database and explore a table.
2. Right-click on NorthwindSQL.
3. Open the Product table
19
Microsoft SQL Server.
SQL Server Management Studio
Creating 0bjects (using a script)
1. Select the COMPANY database and create a new table
2. Click on “New Query”
3. Type code (screen)
4. Hit F5 to execute batch
5. You may also use the GUI interface to “Add New Table”
20
Microsoft SQL Server.
SQL Server Management Studio
Mixing Databases / Temporary Tables
1. Double dot to reach other SQL database table. For example NorthWindSQL..Products
2. Prefix with # a table name to create a temporary table. For example #MyData
21
Microsoft SQL Server.
SQL Server Management Studio
Temporary Tables
Prefix with # a table name to
create a temporary table. For
example #EmpCopy
Notation N’myTable’ indicates
Unicode string (not needed for Germanic – Romance languages)
Examples:
select * into #EmpCopy from employee
create table #Auditing (Clock DateTime, Msg nvarchar1(100) )
Related Topics
Drop Table myTable
If exists (select * from sysObjects where name= N’myTable’)drop table myTable
22
Microsoft SQL Server.
SQL Server Management Studio
Database Diagram
exposing Referential-Integrity
23
-- useful system functionsselect user, current_timestamp, @@servername, @@version
dbo
2006-10-22 14:57:02.233
CARIBE
Microsoft SQL Server 2005 - 9.00.1399.06 (Intel X86) Oct 14 2005 00:33:37 Copyright (c) 1988-2005 Microsoft Corporation Standard Edition on Windows NT 5.1 (Build 2600: Service Pack 2)
Microsoft SQL Server.
Useful Functions
use Company
select db_name()
Company
24
Microsoft SQL Server.
What is T-SQL ?
T-SQLTransac-SQL
25
Microsoft SQL Server.
What is T-SQL ?
T-SQL (Transact-SQL) is a set of programming extensions from Sybase and Microsoft that adds procedural features to the Structured Query Language (SQL) including
• sequential logic, • structured programming, • transaction control, • conditional logic, • iteration, • recursion,• exception and error handling, • row processing, and • declared variables.
Microsoft's SQL Server and Sybase's SQL server support T-SQL statements.
26
Microsoft SQL Server.
T-SQL Language Elements
Transact-SQL element Description
• Identifiers. Names of objects such as tables, views, columns, databases, and servers.• Data Types. Define the types of data that are contained by data objects, such as columns, variables, and parameters. • Functions. Routines that take zero or one or more input values and return a scalar value or a tabular set of values. • Expressions. Units of syntax that SQL Server can resolve to single values. • Operators in Expressions. Work with one or more simple expressions to form a more complex expression. • Comments. Pieces of text included to explain the purpose of the statement. • Reserved Keywords. Words that are reserved for use by SQL Server and should not be used for the names of objects in a database.
27
Regular identifiers
Salary @Salary Salary123 Boss_Salary
Delimited identifiers Are enclosed in double quotation marks (") or brackets ([ ]).
[Big Salary] “StrangeName” [First Name]
Rules for Regular Identifiers1. The first character must be one of the following:
• A letter • The underscore (_), "at" sign (@), or number sign (#). • #Name denotes a temporary table or procedure. • ##Name denotes a global temporary object. • @@Name usually denotes TSQL global functions
2. Other valid symbols are: Letters, digits, @, $, _ (up to 128 char.)
Microsoft SQL Server.
T-SQL IDENTIFIERS
28
Regular identifiers
Salary @Salary Salary123 Boss_Salary
Delimited identifiers Are enclosed in double quotation marks (") or brackets ([ ]).
[Big Salary] “StrangeName” [First Name]
Examples
declare @var1 intdeclare @var2 numeric(10,2), @var3 nvarchar(20)
Microsoft SQL Server.
T-SQL IDENTIFIERS
29
Microsoft SQL Server.
Data Types
Exact
Numerics
Approximate
Numerics
Character
Strings
Unicode
Character Strings
Binary
Strings
Other
Data Types
bigint
decimal
int
numeric
smallint
money
tinyint
smallmoney
bit
float
real
char
text
varchar
nchar
ntext
nvarchar
binary
image
varbinary
cursor
timestamp
sql_variant
uniqueidentifier
table
xml
Datetime
smallDateTime
30
Function category Description
Aggregate Functions (Transact-SQL) Summary operations. Examples are COUNT, SUM, MIN, and MAX.
Configuration functions Scalar functions that return information about configuration settings.
Cryptographic Functions (Transact-SQL) Support encryption, decryption, digital signing, and the validation of digital signatures.
Cursor functions Return information about the status of a cursor.
Date and Time functions Change date and time values.
Mathematical functions Perform trigonometric, geometric, and other numeric operations.
Metadata functions Return information about the attributes of databases and database objects.
Ranking functions Nondeterministic functions that return a ranking value for each row in a partition.
Rowset Functions (Transact-SQL)Return the rowsets that can be used in the place of a table reference in a Transact-SQL statement.
Security functions Return information about users and roles.
String functions Change char, varchar, nchar, nvarchar, binary, and varbinary values.
System functions Operate on or report on various system level options and objects.
System Statistical Functions (Transact-SQL) Return information about the performance of SQL Server.
Text and image functions Change text and image values.
Microsoft SQL Server.
SQL-Server Functions
31
Microsoft SQL Server.
SQL-Server Functions
Aggregation Configuration Cursor Strings
AVG
MIN
CHECKSUM
SUM
CHECKSUM_AGG
STDEV
COUNT
STDEVP
COUNT_BIG
VAR
GROUPING
VARP
MAX
@@DATEFIRST
@@OPTIONS
@@DBTS
@@REMSERVER
@@LANGID
@SERVERNAME
@@LANGUAGE
@@SERVICENAME
@@LOCK_TIMEOUT
@@SPID
@@MAX_CONNECTIONS
@@TEXTSIZE
@@MAX_PRECISION
@@VERSION
@@NESTLEVEL
@@CURSOR_ROWS
@@FETCH_STATUS
CURSOR_STATUS
ASCII
CHAR
CHARINDEX
DIFFERENCE
LEFT
LEN
LOWER
LTRIM
NCHAR
PATINDEX
QUOTENAME
REPLACE
REPLICATE
REVERSE
RIGHT
RTRIM
SOUNDEX
SPACE
STR
STUFF
SUBSTRING
UNICODE
UPPER
32
Microsoft SQL Server.
SQL-Server Functions
Date & Time
Mathematical MetaData
DATEADD
DATEDIFF
DATENAME
DATEPART
DAY
GETDATE
GETUTCDATE
MONTH
YEAR
ABS
ACOS
ASIN
ATAN
ATN2
CEILING
COS
COT
DEGREES
EXP
FLOOR
LOG
LOG10
PI
POWER
RADIANS
RAND
ROUND
SIGN
SIN
SQRT
SQUARE
TAN
@@PROCID
COL_LENGTH
COL_NAME
COLUMNPROPERTY
DATABASEPROPERTY
DATABASEPROPERTYEX
DB_ID
DB_NAME
FILE_ID
FILE_IDEX (Transact-SQL)
FILE_NAME
FILEGROUP_ID
FILEGROUP_NAME
FILEGROUPPROPERTY
FILEPROPERTY
FULLTEXTCATALOGPROPERTY
FULLTEXTSERVICEPROPERTY
INDEX_COL
INDEXKEY_PROPERTY
INDEXPROPERTY
OBJECT_ID
OBJECT_NAME
OBJECTPROPERTY
OBJECTPROPERTYEX
SQL_VARIANT_PROPERTY
TYPE_ID
TYPE_NAME
TYPEPROPERTY
33
Using batches A batch is a group of one or more Transact-SQL statements that are sent from an application to the server as one unit.
Using stored procedures A stored procedure is a group of Transact-SQL statements that have been predefined and precompiled on the server. They can accept parameters, and return result sets, return codes, and output parameters to the caller.
Using triggers A trigger is a special type of stored procedure. It is not called directly by applications. It is instead executed whenever a user performs a specified modification (INSERT, UPDATE, or DELETE) to a table.
Using scripts A script is a series of Transact-SQL statements stored in a file. The file can be used as input to the sqlcmd utility or SQL Server Management Studio Code editor.
Microsoft SQL Server.
Procedural T-SQL
34
Microsoft SQL Server.
Flow-Control, Iteration Statements
BEGIN...END
BREAK
CONTINUE
GOTO
IF...ELSE
RETURN
WAITFOR
WHILE
35
Microsoft SQL Server.
Var Declaration – Assignment Statement
-- assignment operator (SELECT or SET)
declare @var1 int
declare @var2 numeric(10,2), @var3 nvarchar(20)
set @var1= 123
select @var1 = 123 -- same as previous assignment
set @var2 = 19.99
set @var3 = 'Juan Valdez'
set @var2 = CAST(@var1 as numeric(10,2) )
set @var2 = CONVERT(numeric, @var1)
set @var3 = 'Room No. ' + Str(@var1)
36
Microsoft SQL Server.
Flow-Control Statements
BEGIN
statement-1
statement-2
…
statement-n
END
IF @Grade >= 75
print ‘Pass’
ELSE
print ‘Fail’
37
Microsoft SQL Server.
Flow-Control Statements
declare @n int
set @n = 5
WHILE @n > 0
BEGIN
print 'n= ' + str(@n)
set @n = @n - 1
END
declare @n int
select * from employee
set @n = @@rowCount
IF @n = 0
print 'No data found'
ELSE
print 'Total rows: ' + str(@n)
38
The following example uses the DELAY keyword to wait for two seconds before performing a SELECT statement:
WAITFOR DELAY '00:00:02'SELECT * FROM Employee;
The following example uses the TIME keyword to wait until 10 P.M. to perform a check of the Company database to make sure that all Projects are in progress
USE Company;GOBEGIN
WAITFOR TIME '22:00:00';exec CloseTheGates
END;GO
Microsoft SQL Server.
WAITFOR Flow-Control Statements
39
Microsoft SQL Server.
Binding Local Variables with SQL statements
BEGIN
declare @id int
declare @sal money
declare @name nvarchar(20)
select @id = ssn, @sal = salary, @name=fname
from employee
where lname like 'Smith%'
print str(@id) + ' ' + str(@sal) + ' ' + @name
END
Go
40
Microsoft SQL Server.
Binding Local Variables with SQL statements
declare @OldSalary money
update employee
set @OldSalary = salary,
salary = salary + 1
where ssn=123456789
print 'Old salary: ' + str(@OldSalary)
41
Microsoft SQL Server.
Using the global @@ERROR variable
BEGIN
update employee
set salary = salary / 0
where ssn= 123456789
if @@error <> 0
print 'Some bizarre problem ' +
'happened here! - ' +
'call Xagents Mulder & Scully'
END
Msg 8134, Level 16, State 1, Line 2Divide by zero error encountered.The statement has been terminated.Some bizarre problem happend here! - call Mulder and Scully
42
Microsoft SQL Server.
Using the global @@ROWCOUNT variable
Delete employees working for dno 4 (then restore the table)-- create temporary copy of the EMPLOYEE table
select * into #EmpCopy from employee
go
declare @myCount int
BEGIN
begin transaction
delete from #EmpCopy where dno = 4
-- @@rowCount tells how many rows were affected in previous stm.
set @myCount = @@rowCount
if @myCount > 0 begin
select * from #EmpCopy
print 'Deleted rec.= ' + str(@myCount)
rollback
print 'employee table restored'
end
else begin
print 'NO rec. deleted ' + str(@myCount)
commit
end
END
select * from #EmpCopy
43
Microsoft SQL Server.
Using the global @@ROWCOUNT variable
Transaction Processing
Begin Transaction
statement
statement
…
statement
Commit (or Rollback)
44
Microsoft SQL Server.
Using the RAND() Function
delete from mylog
declare @msg varchar(50), @num int, @n int
set @n = 5
while @n > 0
begin
--make a random numb between 1..100
set @num = RAND() * 100 + 1
set @msg = 'Random message number ' + str(@num)
insert into mylog values (@n, @msg)
set @n = @n - 1
end
select * from mylog
45
Microsoft SQL Server.
T-SQL Cursors
T-SQL Cursors
46
Microsoft SQL Server.
T-SQL Cursors
A SQL select-statement retrieves a complete set of rows. Some applications may need a mechanism to work with one row or a small block of rows at a time.
Cursors are an extension to result sets that provide that mechanism by
• 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 to changes made by other users to the database data that is presented in the result set.
• Providing Transact-SQL statements in scripts, stored procedures, and triggers access to the data in a result set.
47
Microsoft SQL Server.
T-SQL Cursors
Syntax
-- drop an existing cursor
deallocate curPeople
-- create a cursor
declare curPeople cursor for
select fname, salary
from employee
where dno = 4
-- open / close cursor
open curPeople
close curPeople
-- fetching rows / checking state
fetch from curPeople into @var1, @var2, ....
@@fetch_status ( 0 when data read )
48
Microsoft SQL Server.
T-SQL Cursors
EXAMPLE-- get first & last name of female employees
deallocate curPeople
declare curPeople cursor for
select fname, lname
from employee
where sex = 'F'
--define local variables to store from cursor
declare @fn nvarchar(20), @ln varchar(20)
open curPeople
fetch from curPeople into @fn, @ln
while(@@fetch_status = 0)
begin
print @fn + ' ' + @ln
fetch from curPeople into @fn, @ln
end
close curPeople
49
deallocate curPeople
Go
declare curPeople cursor for
select fname, salary
from employee
Go
BEGIN TRANSACTION
declare @eName nvarchar(100), @eSal numeric(10,2)
open curPeople
fetch from curPeople into @eName, @eSal
while @@fetch_status = 0 begin
if @eSal < 40000 begin
update employee set salary = salary + 1
where current of curPeople
print 'New salary >>> ' + @eName + str(@eSal)
end
fetch from curPeople into @eName, @eSal
end
close curPeople
ROLLBACK TRANSACTION
Go
Microsoft SQL Server.
T-SQL Forward-Only Cursors
50
--scrollable cursors
deallocate scrPeople
declare scrPeople scroll cursor for
select (fname + N' ' + lname) as fullName, salary from employee order by salary
declare @eName nvarchar(100), @eSal numeric(10,2)
open scrPeople
fetch NEXT from scrPeople into @eName, @eSal
print str(@@fetch_status) + ' ' + @eName + char(9) + str(@eSal)
fetch LAST from scrPeople into @eName, @eSal
print str(@@fetch_status) + ' ' + @eName + char(9) + str(@eSal)
fetch PRIOR from scrPeople into @eName, @eSal
print str(@@fetch_status) + ' ' + @eName + char(9) + str(@eSal)
-- Fetch the second row in the cursor
fetch ABSOLUTE 2 from scrPeople into @eName, @eSal
print str(@@fetch_status) + ' ' + @eName + char(9) + str(@eSal)
-- Fetch the row that is 10 rows after the current row
fetch RELATIVE + 10 from scrPeople into @eName, @eSal
print str(@@fetch_status) + ' ' + @eName + char(9) + str(@eSal)
close scrPeople
Microsoft SQL Server.
T-SQL Scrollable - Cursors
0 Joyce English 302510 James Borg 606370 Jennifer Wallace 474070 Ahmad Jabbar 30251-1 Ahmad Jabbar 30251
51
Microsoft SQL Server.
T-SQL Stored Procedures
T-SQL Stored Procedures
52
Microsoft SQL Server.
T-SQL Stored Procedures with OUTPUT values
IF EXISTS (select * from SYSOBJECTS where name = 'GetDepartment')
DROP PROCEDURE GetDepartment
GO
create procedure GetDepartment (@ID int, @depName nvarchar(20) output)as
BEGIN
select @depName = d.dname from employee e, department d
where e.dno = d.dnumber and e.ssn = @ID
if @@rowCount = 1
return 0 -- department found
else begin
set @depName = ''
return 1 -- department NOT found
end
END
GO
declare @answer nvarchar(20)
Set @answer = '***'
exec GetDepartment 123456789, @answer output
print 'The Department for 123456789 is: ' + @answer
53
Microsoft SQL Server.
T-SQL Stored Procedures with OUTPUT values
declare @answer nvarchar(20)
set @answer = ''
exec GetDepartment 123456789, @answer output
print 'The Department for 123456789 is: ' + @answer
GO
The Department for 123456789 is: Research
declare @myRetCode int
declare @answer nvarchar(20)
set @answer = '***'
set @myRetCode = -1
Execute @myRetCode = GetDepartment 123456789, @answer OUTPUT
print 'The ReturnCode is ' + Str(@myRetCode)
print 'The Department for 123456789 is: ' + @answer
GO
The ReturnCode is 0
The Department for 123456789 is: Research
54
Private Function UseSsnToGetDeptName(ByVal aSSN As Integer) As String
Dim myCnn As New SqlConnectionDim myCmd As New SqlCommand
myCnn.ConnectionString = "Data Source=Localhost;Initial Catalog=Company;Integrated Security=True"myCnn.Open()
myCmd.CommandType = CommandType.StoredProceduremyCmd.Connection = myCnnmyCmd.CommandText = "GetDepartment"
myCmd.Parameters.Clear()myCmd.Parameters.Add("@empSSN", SqlDbType.Int)myCmd.Parameters.Add("@depName", SqlDbType.VarChar, 100)myCmd.Parameters("@depName").Direction = ParameterDirection.Output
myCmd.Parameters("@empSSN").Value = aSSNmyCmd.Parameters("@depName").Value = "***"
myCmd.ExecuteNonQuery()
Return (myCmd.Parameters("@depName").Value)myCnn.Close()
End Function
Microsoft SQL Server. Using a .NET program to reach a
T-SQL Stored Procedures with OUTPUT values
55
Microsoft SQL Server.
T-SQL Stored Procedures with OUTPUT values
-- STORED PROCEDURES: returned values (OUTPUT vars), DEFAULT values
drop procedure pr_GetSalaryGo
create proc pr_GetSalary( @id int,
@sal numeric(20,2) output,@currency nvarchar(10) = 'usd' )
as
declare @ctr int, @xrate numeric(10,2)
BEGIN
set @sal = 0
select @sal = salary from employee where ssn = @id
if @@rowCount = 0 return -1
if @currency = 'usd' set @xrate = 1.00
if @currency = 'euros' set @xrate = 0.73
if @currency = 'bolivares' set @xrate = 2700.00
select @sal = salary from employee where ssn = @id
set @sal = @sal * @xrate
return 0
END
56
Microsoft SQL Server.
T-SQL Stored Procedures with OUTPUT values
--Testing OUTPUT proc and RETURN values
declare @result numeric(20,2), @retCode int
set @result = 0, ret
--no currency supplied (use default 'usd' )
exec pr_GetSalary 987654321, @result output
print 'Salary (usd) = ' + str(@result)
exec pr_GetSalary 987654321, @result output, 'euros'
print 'Salary (euros) = ' + str(@result)
exec pr_GetSalary 987654321, @result output, 'bolivares'
print 'Salary (bolivares) = ' + str(@result)
-- using RETURN CODES. No currency supplied (use default 'usd' )
exec @retCode = pr_GetSalary 123, @result output
print 'Return code is: ' + str(@retCode) + ' Salary (usd) = ' + str(@result)
exec @retCode = pr_GetSalary 123456789, @result output
print 'Return code is: ' + str(@retCode) + ' Salary (usd) = ' + str(@result)
go
Salary (usd) = 47407Salary (euros) = 36977Salary (bolivares) = 118517500
Return code is: -1 Salary (usd) = 0
Return code is: 0 Salary (usd) = 36314
57
Microsoft SQL Server.
T-SQL Stored Functions
drop function dbo.fnGetName
go
CREATE FUNCTION dbo.fnGetName (@aSSN int)RETURNS nvarchar(80)AS BEGIN
-- Returns salutation + full-name of given employeeDECLARE @answer nvarchar(100), @gender nvarchar(2)
set @answer = ''
select @gender = sex from employee where ssn = @aSSN;
if @@rowcount = 0 RETURN @answer;
select @answer = (fname + ' ' + lname) from employee
where ssn = @aSSN;
if @gender = 'F'
set @answer = 'Ms. ' + @answer
else
set @answer = 'Mr. ' + @answer;
RETURN @answer
END;
GO
declare @person nvarchar(100)
set @person = dbo.fnGetName (123456789)print @person
select ssn, dbo.fnGetName(ssn) from employee
58
Imports Microsoft.SqlServer.Server
Imports System.Data.SqlClient
Public Class T
<SqlFunction(DataAccess:=DataAccessKind.Read)> _
Public Shared Function GetFullName(ByVal aSSN As Integer) As Integer
Using conn As New SqlConnection("context connection=true")
conn.Open()
Dim mySQL As String = "SELECT (Fname + ' ' + Lname) as FullName, sex " & _
" FROM Employee WHERE ssn = " & aSSN
Dim cmd As New SqlCommand(mySQL, conn)
Dim DR As SqlDataReader
Dim answer As String = "* * *"
DR = cmd.ExecuteReader()
If DR.Read Then
If DR("sex") = "F" Then
answer = "Ms. " + DR("fullName")
Else
answer = "Mr. " + DR("FullName")
End If
End If
Return answer
End Using
End Function
End Class
Microsoft SQL Server.
CLR Stored Functions
59
drop assembly myFunction
go
CREATE ASSEMBLY myFunction FROM 'c:\temp\SQLCLRfunction.dll'
go
CREATE FUNCTION GetName() RETURNS nvarchar
AS EXTERNAL NAME SQLCLRfunction.T.GetName
go
declare @X nvarchar(100)
SET @x = dbo.GetName()
go
Microsoft SQL Server.
CLR Stored Functions
60
Microsoft SQL Server.
T-SQL Exceptions & RAISERROR command
Error Handling
61
Microsoft SQL Server.
T-SQL Exceptions & RAISERROR command
The command: raiserror behaves like C printf(…)
raiserror(text-message, severity, state, arguments)
Parameters:text-messageseverity(0-18), state(0-127), arguments (used in combination with % formatters)
Example:raiserror('Error. negative argument %d',17, 55, @arg1)
62
Microsoft SQL Server.
T-SQL Exceptions & RAISERROR command
-- EXCEPTIONS. Using RAISERROR command
drop procedure TestError
Go
create procedure TestError (@arg1 int)
as
begin
if @arg1 < 0 begin
--raisError behaves like C printf(…)
--severity(0-18), state(0-127), arguments
raiserror('Error. negative argument %d',17, 55, @arg1)
end
print 'Busy doing something here with ' + str(@arg1)
print 'Adios from your friendly procedure'
end
Go
exec TestError -11
Busy doing something here with -11Adios from your friendly procedureMsg 50000, Level 17, State 55, Procedure TestError, Line 6Error. negative argument -11
Warning: Exception is RAISED but execution continues !
63
Microsoft SQL Server.
T-SQL Exceptions & RAISERROR command-- EXCEPTIONS. Using RAISERROR command
drop procedure pr_Spouse
Go
create procedure pr_Spouse (@id int, @spouseName nvarchar(20) output)
as
BEGIN
set @spouseName = '***'select * from employee where ssn = @id
if @@rowCount=0 begin
--message like C printf, severity(0-18), state(0-127), arguments
raiserror('Error1. Invalid employee SSN %d',17, 55, @id)
-- raiserror('Error2. Invalid employee SSN %d',17, 55, @id)
-- raiserror('Error3. Invalid employee SSN %d',17, 55, @id)
-- return 1
end
select @spouseName = dependent_name
from dependent
where relationship = 'Spouse' and essn = @id
if @@rowCount=0
return 2
else
return 0
END
go
declare @mate nvarchar(40), @retCode int
execute @retCode = pr_Spouse 123, @mate output
print 'Spouse: ' + @mate + ' - Return Code: ' + ltrim(str(@retCode))
(0 row(s) affected)Spouse: *** Return Code: 1Msg 50000, Level 17, State 55, Procedure pr_Spouse, Line 9Error. Invalid employee SSN 123
64
Imports System.Data.SqlClient
Public Class Form1
Private Sub btnFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnFind.Click
Try
Dim myCnn As New SqlConnection
Dim myCmd As New SqlCommand
myCnn.ConnectionString = "Data Source=Localhost;Initial Catalog=CompanySQL;
Integrated Security=True"
myCnn.Open()
myCmd.CommandType = CommandType.StoredProcedure
myCmd.CommandText = "pr_Spouse"
myCmd.Connection = myCnn
myCmd.Parameters.Clear()
myCmd.Parameters.Add("@id", SqlDbType.BigInt)
myCmd.Parameters.Add("@spouseName", SqlDbType.VarChar, 20)
myCmd.Parameters("@spouseName").Direction = ParameterDirection.Output
myCmd.Parameters("@id").Value = Me.txtSSN.Text
myCmd.Parameters("@spouseName").Value = "***"
Dim myReturnCode As Integer
myReturnCode = myCmd.ExecuteNonQuery
Me.txtSpouse.Text = myCmd.Parameters("@spouseName").Value
myCnn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
Microsoft SQL Server.
T-SQL Exceptions & RAISERROR command
65
Microsoft SQL Server.
T-SQL Transactions
Transaction Processing
66
Microsoft SQL Server.
T-SQL Transactions
What is a transaction?
A transaction is a group of statements treated as a monolithic block that must either succeed or fail in its integrity.
Example --Transfer $1M from saving to checking account
Problem. If the first statement succeeds but the second statement fails the customer looses $1M
BEGINExecute Procedure to Withdraw $1M from SavingAccount XYZ_SAVExecute Procedure to Deposit $1M into CheckingAccount XYZ_CHK
END
67
Microsoft SQL Server.
T-SQL Transactions
Solution--Transfer $1M from saving to checking account as a Transaction
BEGIN TRANSACTION
Execute Procedure to Withdraw $1M from SavingAccount XYZSAVExecute Procedure to Deposit $1M into CheckingAccount XYZCHK
COMMIT TRANSACTION
• The two operations are treated as a single (indivisible/atomic) statement.
• The two of them MUST satisfactorily execute or both of them will be rolled-back and the changes they made will be UNDONE.
68
Microsoft SQL Server.
T-SQL Transactions
Transaction Control Statements
Begin Transaction Marks the beginning of a critical region.
Commit Transaction Make changes be permanent.
Rollback Transaction Undo all changes up to begin tran or save-point.
Save Transaction <Label> Marks a save-point for partial rollbacks
69
Microsoft SQL Server.
Transaction Control Statements
Transaction Control Statement Effect on @@tranCount
Begin Tran
Commit Tran
Rollback [Tran]
RollBack [Tran <savepoint name>]
Save Tran [<savepoint name>]
+1
-1
Reset to 0
None
none
70
Microsoft SQL Server.
T-SQL Transactions
Example
declare @myCount int
--STEP1. How many Projects are there?select @myCount = count(*) from project
print 'Num. Projects= ' + str(@myCount)
BEGIN TRANSACTION
--STEP2. Add a new Projectinsert into Project values ('Bogus Project',0, 'NY',1)
select @myCount = count(*) from project
print 'Num. Projects= ' + str(@myCount)
ROLLBACK TRANSACTION
--STEP1. How many Projects are there?select @myCount = count(*) from project
print 'Num. Projects= ' + str(@myCount)
Num. Projects= 6
(1 row(s) affected)Num. Projects= 7
Num. Projects= 6
71
Microsoft SQL Server.
T-SQL Transactions
EXAMPLE. Transfer $1M from saving to checking accountdrop table #BankAccount
create table #BankAccount ( No integer, Type nvarchar(10), Balance money)
insert into #BankAccount values (111, 'Saving', 900000)
insert into #BankAccount values (111, 'Checking', 20)
insert into #BankAccount values (222, 'Checking', 100)
go
select * from #BankAccount
go
Begin transaction
declare @savingBalance money
--subtract $1M from saving account
update #BankAccount set balance = balance - 1000000 where No= 111 and Type = 'Saving'
select @savingBalance = balance from #BankAccount where No= 111 and Type = 'Saving'
--deposit $1M into checking account
update #BankAccount set balance = balance - 1000000 where No= 111 and Type = 'Checking'
--finish the transfer operation
if @savingBalance >= 0 begin
print 'Successful transfer operation'
commit tran
end
else begin
print 'Problem. Insufficient (saving) funds '
rollback tran
end
print 'Thanks for using our bank'
select * from #BankAccount
Problem. Insufficient (saving) funds Thanks for using our bank
72
Microsoft SQL Server.
T-SQL Transactions
Implicit TransactionsThe commands listed in the table below are executed in isolation as a complete and self-contained transaction.
<begin tran>Database_command
<commit tran>
ALTER TABLE FETCH REVOKE
CREATE GRANT SELECT
DELETE INSERT TRUNCATE TABLE
DROP OPEN UPDATE
To change this behavior use the command
SET IMPLICIT_TRANSACTIONS { ON | OFF }
73
Microsoft SQL Server.
T-SQL Transactions
Error Checking in Transactions
The global variable @@error returns the error number for the last Transact-SQL statement executed.
begin tran
update employee set salary = salary / 0
if @@error <> 0 begin
print 'Problems – but ready to roll'
rollback tran
end
print 'Last Line'
Msg 8134, Level 16, State 1, Line 3Divide by zero error encountered.The statement has been terminated.Problems – but ready to rollLast Line
74
Microsoft SQL Server.
T-SQL Transactions
USING SAVEPOINTSdrop table #temp
select * into #Temp from works_on where essn = -1
Go
begin tran
save tran Step1
insert into #temp values(1,1,1)
save tran Step2
insert into #temp values(2,2,2)
save tran Step3
insert into #temp values(3,3,3)
rollback tran
select * from #temp
begin tran
save tran Step1
insert into #temp values(1,1,1)
save tran Step2
insert into #temp values(2,2,2)
save tran Step3
insert into #temp values(3,3,3)
rollback tran Step2
select * from #temp
75
Microsoft SQL Server.
T-SQL Exceptions & RAISERROR command
-- EXCEPTIONS. Using RAISERROR command
declare @person nvarchar(20), @code int
set @code = 0
exec @code = pr_Spouse 666884444, @person output
print 'Spouse name: ' + @person + ' Ret code: ' + str(@code)
exec @code = pr_Spouse 987654321, @person output
print 'Spouse name: ' + @person + ' Ret code: ' + str(@code)
exec @code = pr_Spouse 123, @person output
print 'Spouse name: ' + @person + ' Ret code: ' + str(@code)
Spouse name: Ret code: 2Spouse name: Abner Ret code: 0Spouse name: Ret code: 2
Msg 50000, Level 17, State 55, Procedure pr_Spouse, Line 8Error. Invalid SSN 123
76
Microsoft SQL Server.
T-SQL Recursion
drop procedure recurFactorial
go
create procedure RecurFactorial (@n int, @result int output)
as
BEGIN
declare @nminus1 int
print 'n ' + str(@n) + ' result: ' + str(@result)
if @n = 1 begin
set @result = 1
return
end
set @nminus1 = @n - 1
exec RecurFactorial @nminus1, @result output
set @result = @n * @result
print 'n ' + str(@n) + ' result: ' + str(@result)
return
END
go
declare @arg int; set @arg = 0
exec RecurFactorial 4, @arg output
print 'Arg: ' + str(@arg)
n 4 result: 0n 3 result: 0n 2 result: 0n 1 result: 0n 1 result: 2n 2 result: 6n 3 result: 24Arg: 24
77
Microsoft SQL Server.
T-SQL TRIGGERS
T-SQL Triggers
78
Microsoft SQL Server.
T-SQL TRIGGERS
Insert into works_on(Essn,Pno, Hours) values (123456789, 10, 40);
WORKS_ON table
ESSN PNO HOURS
--------- ---------- ----------
123456789 1 32.5
123456789 2 7.5
666884444 3 40
453453453 1 20
453453453 2 20
333445555 2 10
333445555 3 10
333445555 10 10
333445555 20 10
999887777 30 30
999887777 10 10
987987987 10 35
987987987 30 5
987654321 30 20
987654321 20 15
888665555 20 0
TRIGGER T008BON WORKS_ON AFTER UPDATE
AS BEGIN. . . END
TRIGGER Trg_NoOverload ON WORKS_ON AFTER INSERT
AS BEGIN--Employees can not work more than 40 hours/week. . .. . .END;
Msg 3609, Level 16, State 1, Line 2The transaction ended in the trigger. The batch has been aborted.
Msg 50000, Level 17, State 55, Procedure Trg_NoOverload, Line 23
Violation to rule: max 40 hrs/week 123456789
79
Microsoft SQL Server.
T-SQL TRIGGERS
Microsoft SQL Server 2005 provides two primary mechanisms for enforcing business rules and data integrity• constraints and • triggers.
A trigger is a special type of stored procedure that automatically takes effect when a language event executes. SQL Server includes two general types of triggers: • DML triggers and • DDL triggers.
SQL Server allows for creating multiple triggers for any specific statement.
Note: Constrains include clauses such as: Primary and Foreign Keys, Nulls, Duplicates, Check, etc.
80
Microsoft SQL Server.
T-SQL TRIGGERS
CREATE TABLE table_name
( { < column_definition > | < table_constraint > } [ ,...n ] )
< column_definition > ::=
{ column_name data_type } [ { DEFAULT constant_expression
| [ IDENTITY [ ( seed , increment ) ] ] } ]
[ ROWGUIDCOL ]
[ < column_constraint > [ ...n ] ]
< column_constraint > ::= [ CONSTRAINT constraint_name ]
{ [ NULL | NOT NULL ]
| [ PRIMARY KEY | UNIQUE ]
| REFERENCES ref_table [ ( ref_column ) ]
[ ON DELETE { CASCADE | NO ACTION } ]
[ ON UPDATE { CASCADE | NO ACTION } ]
}
< table_constraint > ::= [ CONSTRAINT constraint_name ]
{ [ { PRIMARY KEY | UNIQUE }
{ ( column [ ,...n ] ) }
]
| FOREIGN KEY
( column [ ,...n ] )
REFERENCES ref_table [ ( ref_column [ ,...n ]
) ]
[ ON DELETE { CASCADE | NO ACTION } ]
[ ON UPDATE { CASCADE | NO ACTION } ]
}
Basic Referential Integrity & Column Constraints
Triggers extend this type of simpleconstraints
81
Microsoft SQL Server.
T-SQL TRIGGERS
DDL triggers are invoked when a data definition language (DDL) event takes place in the server or database (CREATE, DROP, ALTER,…).
DML triggers are invoked when a data manipulation language (DML) event takes place in the database.
1. DML events include INSERT, UPDATE, or DELETE statements that modify data in a specified table or view.
2. A DML trigger can query other tables and can include complex Transact-SQL statements.
3. The trigger and the statement that fires it are treated as a single transaction, which can be rolled back from within the trigger.
4. If a severe error is detected (for example, insufficient disk space), the entire transaction automatically rolls back.
82
Microsoft SQL Server.
T-SQL TRIGGERS
DML triggers are useful in these ways:
1. They can cascade changes through related tables in the database.
2. They can guard against malicious or incorrect INSERT, UPDATE, and DELETE operations and enforce other restrictions that are more complex than those defined with CHECK constraints.
3. Unlike CHECK constraints, DML triggers can reference columns in other tables.
4. They can evaluate the state of a table before and after a data modification and take actions based on that difference.
5. Multiple DML triggers of the same type (INSERT, UPDATE, or DELETE) on a table allow multiple, different actions to take place in response to the same modification statement.
83
Microsoft SQL Server.
T-SQL TRIGGERS
Kinds of DML Triggers
AFTER TriggersAFTER triggers are executed after the action of the INSERT, UPDATE, or
DELETE statement is performed (same as FOR used in earlier versions of Microsoft SQL Server). AFTER triggers can be specified only on tables.
INSTEAD OF TriggersINSTEAD OF triggers are executed in place of the usual triggering action.
They can also be defined on views with one or more base tables, where they can extend the types of updates a view can support.
CLR Triggers (Common Language Runtime)
A CLR Trigger can be either an AFTER or INSTEAD OF trigger. A CLR trigger can also be a DDL trigger. Instead of executing a Transact-SQL stored procedure, a CLR trigger executes one or more methods written in managed code that are members of an assembly created in the .NET Framework and uploaded in SQL Server.
84
Microsoft SQL Server.
T-SQL TRIGGERS
Function AFTER trigger INSTEAD OF trigger
Applicability Tables Tables and views
Quantity per table or view Multiple per triggering action (UPDATE, DELETE, and INSERT)
One per triggering action (UPDATE, DELETE, and INSERT)
Cascading references No restrictions apply INSTEAD OF UPDATE and DELETE triggers are not allowed on tables that are targets of cascaded referential integrity constraints.
Execution After:
1. Constraint processing
2. Declarative referential actions
3. inserted and deleted tables creation
4. The triggering action
Before: Constraint processing
In place of: The triggering action
After: inserted and deleted tables creation
Order of execution First and last execution may be specified Not applicable
varchar(max), nvarchar(max), and varbinary(max) column references in inserted and deleted tables
Allowed Allowed
text, ntext, and image column references in inserted and deleted tables
Not allowed Allowed
85
DML TRIGGER SYNTAXTrigger on an INSERT, UPDATE, or DELETE statement to a table or view
CREATE TRIGGER [ schema_name . ]trigger_name
ON { table | view }
[ WITH <dml_trigger_option> [ ,...n ] ]
{ FOR | AFTER | INSTEAD OF }
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
[ WITH APPEND ]
[ NOT FOR REPLICATION ]
AS { sql_statement [ ; ] [ ...n ] | EXTERNAL NAME <method
specifier [ ; ] > }
<dml_trigger_option> ::=
[ ENCRYPTION ]
[ EXECUTE AS Clause ]
<method_specifier> ::=
assembly_name.class_name.method_name
Microsoft SQL Server.
T-SQL TRIGGERS
86
Microsoft SQL Server.
T-SQL TRIGGERS
Example. No employee should work on more than 4 assignments
CREATE TRIGGER Trg_MaxFourJobs
ON Works_On AFTER INSERT
AS BEGIN
-- no employee should work on more than four projects
if exists(select * from works_on
group by essn having count(*) > 4)
begin
raiserror('Error. More than 4 assignments', 17,55)
rollback tran
end
END
GO
87
Microsoft SQL Server.
T-SQL TRIGGERS
Example. No employee should work on more than 4 assignments (cont.)
-- testing the trigger
select essn, count(*)as jobs
from works_on group by essn
insert into works_on
values (333445555,1,1)
Go
select essn, count(*)as jobs
from works_on group by essn
Go
Msg 3609, Level 16, State 1, Line 2The transaction ended in the trigger. The batch has been aborted.
Msg 50000, Level 17, State 55, Procedure Trg_MaxFourJobs, Line 8Volation. More than four assignments
88
Microsoft SQL Server.
T-SQL TRIGGERS
DELETED and INSERTED tables
The SQL-Server provides two memory-resident tables called INSERTEDand DELETED to test the effects of certain data modifications and to set conditions for DML trigger actions.
You cannot directly modify the data in the tables or perform data definition language (DDL) operations on the tables, such as CREATE INDEX.
In DML triggers, the inserted and deleted tables are primarily used to perform the following:
1. Extend referential integrity between tables.2. Insert or update data in base tables underlying a view.3. Test for errors and take action based on the error.4. Find the difference between the state of a table before and after a
data modification and take actions based on that difference.
89
Microsoft SQL Server.
T-SQL TRIGGERS
DELETED and INSERTED tables
The deleted table stores copies of the affected old rows during DELETEand UPDATE statements.
During the execution of a DELETE or UPDATE statement, old rows are deleted from the trigger table and transferred to the deleted table.
The inserted table stores copies of the affected new rows during INSERTand UPDATE statements.
During an insert or update transaction, new rows are added at the same time to both the inserted table and the trigger table. The new rows in the inserted table are copies of the new rows in the trigger table.
90
Microsoft SQL Server.
T-SQL TRIGGERS
DELETED and INSERTED tables
An update transaction is similar to a delete operation followed by an insertoperation; the old rows are copied to the deleted table first, and then the new rows are copied to the trigger table and to the inserted table.
Table \ Operation insert delete update
INSERTED Yes Empty Yes
DELETED Empty Yes Yes
91
Microsoft SQL Server.
T-SQL TRIGGERS
Example1A. Spying on the INSERTED and DELETED tables
CREATE TRIGGER Trg_SpyInsertedDeleted
ON Project AFTER UPDATE
AS BEGIN
-- spying on the DELETED and UPDATED tables
select * from inserted
select * from deleted
select * from Project
END
GO
update Project set Pname = upper(Pname) where Dnum = 4
92
Microsoft SQL Server.
T-SQL TRIGGERS
Example1A. Spying on the INSERTED and DELETED tables
INSERTED(new images)
DELETED(old images)
Updated version of the PROJECT table
93
Microsoft SQL Server.
T-SQL TRIGGERS
Example1B. Spying on the INSERTED and DELETED tables
DROP TRIGGER Trg_SpyInsertedDeleted
GO
CREATE TRIGGER Trg_SpyInsertedDeleted
ON Project AFTER UPDATE
AS BEGIN
-- spying on the DELETED and UPDATED tables
select 'Inserted', * from inserted
select 'Deleted', * from deleted
select 'Modified', * from Project
END
GO
BEGIN TRANSACTION
select 'Before update', * from Project
update Project set Pname = upper(Pname) where Dnum = 4
select 'After update', * from Project
ROLLBACK TRANSACTION
GO
select 'After Rollback', * from Project
Go
94
Microsoft SQL Server.
T-SQL TRIGGERS
Example1B1. Spying on the INSERTED and DELETED tables
95
Microsoft SQL Server.
T-SQL TRIGGERS
Example1B2. Spying on the INSERTED and DELETED tables
96
Microsoft SQL Server.
T-SQL TRIGGERS
Example1B3. Spying on the INSERTED and DELETED tables
97
Microsoft SQL Server.
T-SQL TRIGGERS
Example2. Spying on the INSERTED and DELETED tables CREATE TRIGGER Trg_SpyInsertedDeleted2
ON ProjectCopy AFTER DELETE
AS BEGIN
-- spying on DELETED and UPDATED
select 'inserted', * from inserted
select 'deleted', * from deleted
select * from ProjectCopy
END
GO
select * from ProjectCopy
go
delete from ProjectCopy where Dnum = 4
98
Microsoft SQL Server.
T-SQL TRIGGERS
Example3. Employees should not work more than 40 hrs/week
-- See trigger code on next page ⇒⇒⇒⇒
select * , 'Before insert' from works_on where essn = 123456789GO
BEGIN TRANSACTION
-- Testing the trigger Trg_NoOverload
insert into works_on values (123456789,10,60)
ROLLBACK TRANSACTION
GO
select *, 'After insert' from works_on where essn = 123456789
99
Microsoft SQL Server.
T-SQL TRIGGERS
DROP TRIGGER Trg_NoOverload GO
CREATE TRIGGER Trg_NoOverload ON WORKS_ON AFTER INSERTAS BEGIN
declare @essn integer, @totalHours float, @Problems int
declare curHours cursor forselect essn, sum(Hours) as totalHours from works_on where essn in (select essn from inserted)group by essn
--just for testing/debugging
select *, 'inserted' from insertedselect *, 'deleted' from deletedselect essn, sum(Hours) as totalHours from works_on group by essn
100
Microsoft SQL Server.
T-SQL TRIGGERS
-- CONTINUATION OF: CREATE TRIGGER Trg_NoOverload ON WORKS_ON…
--check if currently inserted records exceed sum-hours > 40
set @Problems = 0
if OBJECT_ID('curHours') is not nullDeallocate curHours
open curHoursfetch from curHours into @essn, @totalHourswhile (@@fetch_status = 0) begin
if (@totalHours > 40) beginset @Problems = 1raiserror ('Violation to rule: max 40 hrs/week %d ',17,55,@essn)end
fetch from curHours into @essn, @totalHoursend
if @Problems = 1 rollback transactionEND
101
Microsoft SQL Server.
T-SQL TRIGGERS
Example3. Employees should not work more than 40 hrs/week
Original WORKS_ON records for 123456789
INSERTED table
DELETED table
WORKS_ON table as seen internally by the trigger after performing the insertion ( just before rollback ).
102
Microsoft SQL Server.
T-SQL TRIGGERS
The UPDATE( ) Function
Returns a Boolean value that indicates whether an INSERT or UPDATEattempt was made on a specified column of a table or view.
UPDATE() is used anywhere inside the body of a Transact-SQL INSERT or UPDATE trigger to test whether the trigger should execute certain actions.
Syntax
UPDATE ( column )
103
Microsoft SQL Server.
T-SQL TRIGGERS
Example4. Using the UPDATE( ) function
CREATE TRIGGER Trg_SpyUpdateFunction
ON ProjetCopy AFTER UPDATE, INSERT
AS BEGIN
-- spying on the DELETED and UPDATED tables
select 'inserted', * from inserted
select 'deleted', * from deleted
select * from ProjetCopy
if UPDATE(pLocation) print 'Location was changed'
if UPDATE(pName) print 'Project name was changed'
END
GO
select * from ProjetCopy where dnum = 4
go
update ProjetCopy set pLocation = 'Cleveland' where dnum = 4
104
Microsoft SQL Server.
T-SQL TRIGGERS
Example4. Using the UPDATE( ) function
update ProjetCopy set pLocation = 'Cleveland' where Dnum = 4
105
Microsoft SQL Server.
T-SQL TRIGGERS
CASCADED updates and deletesTriggers can be used to enforce non-elementary cases of referential integrity
ExampleDelete an employee may imply a complex sequence of operations including
- Erase family members (or perhaps save records in a historical table)- Remove all his assignments- If the employee is a supervisor, find his immediate supervisor and assign
him/her (at least temporarily) to his supervisees
106
Microsoft SQL Server.
T-SQL TRIGGERS
Example1. CASCADED updates and deletesPreparation for demonstrating the removal of dependents
-- is there already a temp #FAMILY table?. If not you must create it
if not exists(select * from tempdb..sysobjects where name like '#Family%')
begin
select * into #Family from DependentCopy where essn = 0
delete from #Family
end
Go
drop table DependentCopy
drop table EmployeeCopy
Go
--make copies of the Employee and Dependent tables
select * into DependentCopy from Dependent
select * into EmployeeCopy from Employee
Go
drop trigger trg_RemoveFamily
Go
107
Microsoft SQL Server.
T-SQL TRIGGERS
Example1. CASCADED updates and deletes (cont.)
create trigger trg_RemoveFamily on EMPLOYEEcopy after delete
as begin
-- copy dependent rec. into #Family for each deleted employee
insert into #family select * from DependentCopy
where essn in (select ssn from deleted)
-- now remove those dependent records
delete from DependentCopy
where essn in (select ssn from deleted)
if @@error <> 0 begin
raiserror('Problem during removal of family records',17,55)
rollback tran
end
end
go
select 'DependentCopy before',* from dependentCopy
go
delete from EmployeeCopy where ssn in (123456789, 987654321)
go
select '#Family', * from #Family
select 'DependentCopy after',* from DependentCopy
select 'EmployeeCopy', * from EmployeeCopy
108
Microsoft SQL Server.
T-SQL TRIGGERS
Example1. CASCADED updates and deletes (cont.)Removing Employees (123456789 & 987654321) and cascading on Dependents
109
Microsoft SQL Server.
T-SQL TRIGGERS
Example2. CASCADED updates and deletes
Business rule: If a supervisor is removed her immediate supervisor should be automatically assigned to her supervisees.
--make the supervisor of a removed supervisor take charge
create trigger trg_NewBoss on EMPLOYEECOPY after Delete
as begin
declare @boss nvarchar(50), @biggerBoss nvarchar(50)
declare curBiggerBoss cursor for
select distinct b.ssn as boss, b.superssn as biggerBoss
from Deleted b
open curBiggerBoss
fetch from curBiggerBoss into @boss, @biggerBoss
while @@fetch_status = 0 begin
update employeeCopy set superssn = @biggerBoss where superssn = @boss
fetch from curBiggerBoss into @boss, @biggerBoss
end
close curBiggerBoss
end
110
Microsoft SQL Server.
T-SQL TRIGGERS
Example2. CASCADED updates and deletes
-- preparation and testing
drop table employeeCopy
select 'before' , * into employeeCopy
from employee
Go
-- delete wakes up the trigger
delete from employeecopy
where ssn = 987654321
Go
-- show results
select ' after', ssn,superssn from employeecopy