Upload
buikien
View
219
Download
0
Embed Size (px)
Citation preview
SQL Server Triggers
© Meganadha Reddy K., 2015 http://www.netcomlearning.com/
Meganadha Reddy K.Technical Trainer | NetCom Learning
www.NetComLearning.com
Agenda
• SQL Server Objects
• SQL Server Constraints
• Triggers
• Types of Triggers
• Demos
• Q & A
© Meganadha Reddy K., 2015 http://www.netcomlearning.com/
SQL Server Objects
© Meganadha Reddy K., 2015 http://www.netcomlearning.com/
Tables
Views Columns
Constraints
Functions
Stored Procedures
Triggers
Joins
SysTables
Logins
indexes
Transactions
Backups
TABLES
• Rows and Columns
• A database will have at least one table.
© Meganadha Reddy K., 2015 http://www.netcomlearning.com/
EmpId EmpName EmpDept
1 Meg IT
2 Harry Sales
3 Llew Admin
Constraints
• Primary Key : Unique way to differentiate each row of a table.
• Unique Key : Same as above but allows null value only once
• Not Null
• Default
• Check
SysTables
In Software Projects we frequently use below:
Sys.Columns
Sys.Objects
SysComments
© Meganadha Reddy K., 2015 http://www.netcomlearning.com/
Additional Objects
© Meganadha Reddy K., 2015 http://www.netcomlearning.com/
• Stored Procedures
• Functions
• Views
• Triggers
• Cursors
• Joins : To retrieve data from more than one table
TRIGGERS
© Meganadha Reddy K., 2015 http://www.netcomlearning.com/
Triggers
Instead of TriggersAfter Triggers
Insert Update Delete Insert Update Delete
Demo : Trigger (1 of 3)
• Lets take table : Employee
CREATE TABLE Employee
(
Emp_ID INT Identity,
Emp_name Varchar(100),
Emp_Sal Decimal (10,2)
)
INSERT INTO Employee VALUES (‘James',1200);
INSERT INTO Employee VALUES (‘Nick',1400);
INSERT INTO Employee VALUES (‘Raj',1000);
INSERT INTO Employee VALUES (‘Ravi',1100);
INSERT INTO Employee VALUES (‘Llew',1500);
© Meganadha Reddy K., 2015 http://www.netcomlearning.com/
Demo : Trigger (2 of 3)
CREATE TABLE Employee_Audit
(
Emp_ID int,
Emp_name varchar(100),
Emp_Sal decimal (10,2),
Audit_Action varchar(100),
Audit_Timestamp datetime
)
© Meganadha Reddy K., 2015 http://www.netcomlearning.com/
Demo : Trigger (3 of 3)
CREATE TRIGGER trgAfterInsert ON [dbo].[Employee] FOR INSERT
AS
declare @empid int;
declare @empname varchar(100);
declare @empsal decimal(10,2);
declare @audit_action varchar(100);
select @empid=i.Emp_ID from inserted i;
select @empname=i.Emp_Name from inserted i;
select @empsal=i.Emp_Sal from inserted i;
set @audit_action='Inserted Record -- After Insert Trigger.';
insert into Employee_Audit
(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values(@empid,@empname,@empsal,@audit_action,getdate());
PRINT 'AFTER INSERT trigger fired.'
GO
© Meganadha Reddy K., 2015 http://www.netcomlearning.com/
Triggers
More Demos
© Meganadha Reddy K., 2015 http://www.netcomlearning.com/
Q & A
?
© Meganadha Reddy K., 2015 http://www.netcomlearning.com/