inserted table Demo : Inserted table « Trigger « SQL Server / T-SQL Tutorial

Home
SQL Server / T-SQL Tutorial
1.Query
2.Insert Delete Update
3.Table
4.Table Join
5.Data Types
6.Set Operations
7.Constraints
8.Subquery
9.Aggregate Functions
10.Date Functions
11.Math Functions
12.String Functions
13.Data Convert Functions
14.Analytical Functions
15.Sequence Indentity
16.View
17.Index
18.Cursor
19.Database
20.Transact SQL
21.Procedure Function
22.Trigger
23.Transaction
24.XML
25.System Functions
26.System Settings
27.System Tables Views
28.User Role
29.CLR
SQL Server / T-SQL Tutorial » Trigger » Inserted table 
22.15.1.inserted table Demo
7>
8CREATE TABLE Employees
9(
10>   empid     int          NOT NULL,
11>   mgrid     int          NULL,
12>   empname   varchar(25)  NOT NULL,
13>   salary    money        NOT NULL,
14>   lvl       int          NULL,
15>   hierarchy varchar(900NULL
16)
17> GO
1>
2CREATE TRIGGER myTrigger ON Employees FOR INSERT
3> AS
4> DECLARE @numrows AS int
5> SET @numrows = @@ROWCOUNT
6> IF @numrows > 1
7BEGIN
8>   RAISERROR('Only single row inserts are supported!', 161)
9>   ROLLBACK TRAN
10END
11> ELSE
12> IF @numrows = 1
13BEGIN
14>   UPDATE E
15>     SET lvl = CASE
16>                 WHEN E.mgrid IS NULL THEN 0
17>                 ELSE M.lvl + 1
18>               END,
19>         hierarchy = CASE
20>                       WHEN E.mgrid IS NULL THEN '.'
21>                       ELSE M.hierarchy
22>                     END + CAST(E.empid AS varchar(10)) '.'
23FROM
24>     Employees AS E
25>   JOIN
26>     inserted AS I ON I.empid = E.empid
27>   LEFT OUTER JOIN
28>     Employees AS M ON E.mgrid = M.empid
29END
30> GO
1>
2> --Testing the myTrigger Trigger
3>
4INSERT INTO employees(empid, mgrid, empname, salaryVALUES(1512'Sean', $1500.00)
5> GO

(rows affected)
1> drop table Employees;
2> GO
1>
22.15.Inserted table
22.15.1.inserted table Demo
22.15.2.Inserted, deleted pseudo table
22.15.3.COUNT(*) FROM Inserted
22.15.4.Join Inserted table with real table
22.15.5.Count Inserted table
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.