Presentation is loading. Please wait.

Presentation is loading. Please wait.

T-sql triger examples.  Öğrenci eklendiğinde mesaj veren triger CREATE TRIGGER trigAddStudents ON Students FOR INSERT AS VARCHAR(100)

Similar presentations


Presentation on theme: "T-sql triger examples.  Öğrenci eklendiğinde mesaj veren triger CREATE TRIGGER trigAddStudents ON Students FOR INSERT AS VARCHAR(100)"— Presentation transcript:

1 T-sql triger examples

2  Öğrenci eklendiğinde mesaj veren triger CREATE TRIGGER trigAddStudents ON Students FOR INSERT AS DECLARE @Newname VARCHAR(100) SELECT @Newname =(SELECT Name FROM INSERTED) PRINT 'THE STUDENT ' + @Newname + ' IS ADDED.';

3  This sample code will copy a field (column) to another field when a new row is inserted or updated. CREATE TRIGGER test ON tbltest FOR INSERT, UPDATE AS BEGIN UPDATE tblTest SET tbltest.testvalue=tbltest.name FROM INSERTED WHERE inserted.id=tbltest.id END

4 Enable/Disable  ENABLE/DISABLE TRIGGER trgName ON tblNAme

5  If a customer's overall sales amount is less than 10,000 $ then mark the customer priority field with 3. If the total amount is between 10,000 and 50,000 then the customer priority should be set to 2. If a more sales amount is reached for that customer, the customer priority database field should be 1. Note that if no sales transaction has been created yet, that customer will not have any priority (priority sql field will be NULL).

6  CREATE TABLE Customers ( CustomerId smallint identity(1,1), Name nvarchar(255), Priority tinyint ) CREATE TABLE Sales ( TransactionId smallint identity(1,1), CustomerId smallint, [Net Amount] int, Completed bit )

7  WITH CTE AS ( select CustomerId from inserted union select CustomerId from deleted ) UPDATE Customers SET Priority =... -- we will complete here soon FROM Customers c INNER JOIN CTE ON CTE.CustomerId = c.CustomerId

8  The sql CTE select statement returns the list of customers affected by Insert, Delete and Update sql command.,  Here is an sql code from SQL Server 2008 trigger example that will get sum of sales transaction amount.

9  select CustomerId, SUM([Net Amount]) Total from Sales inner join CTE on CTE.CustomerId = Sales.CustomerId where Completed = 1 group by Sales.CustomerId

10 SQL Code of SQL Trigger AFTER Insert, Update, Delete  CREATE TRIGGER dbo.Update_Customer_Priority ON dbo.Sales AFTER INSERT, UPDATE, DELETE AS WITH CTE AS ( select CustomerId from inserted union select CustomerId from deleted ) UPDATE Customers SET Priority = case when t.Total 50000 then 1 when t.Total IS NULL then NULL end FROM Customers c INNER JOIN CTE ON CTE.CustomerId = c.CustomerId LEFT JOIN ( select Sales.CustomerId, SUM([Net Amount]) Total from Sales inner join CTE on CTE.CustomerId = Sales.CustomerId where Completed = 1 group by Sales.CustomerId ) t ON t.CustomerId = c.CustomerId  go

11  insert into Customers select N'MS SQL Server Team', NULL insert into Customers select N'MS Windows Team', NULL insert into Customers select N'MS Internet Explorer Team', NULL  insert into Sales select 1, 5000, 1

12  insert into Sales select 2, 45000, 1  insert into Sales select CustomerId, 7500, 1 from Customers

13  update Sales set Completed = 0

14 Example 2  The goal of the trigger is to update the value in LogSum_Count every time the AboutUs.htm and Services.htm pages are accessed.

15  CREATE TABLE InetLog (ClientHost varchar(255), LogTime datetime, Target varchar(255)) go CREATE TABLE LogSummary (LogSum_Category varchar(30), LogSum_Count int) go INSERT LogSummary VALUES ('About Us',0) INSERT LogSummary VALUES ('Services',0)

16

17

18 UPDATE Trigger

19 CREATE TRIGGER trgFillInMissingCouponRate ON [dbo].StateTaxFreeBond FOR INSERT,UPDATE AS BEGIN UPDATE StateTaxFreeBondArchive SET CouponRate = isnull(i.CouponRate,m.CouponRate) FROM StateTaxFreeBondArchive m INNER JOIN inserted i ON m.MBCID = i.MBCID END

20 Instead of trigger

21 Index yapısı  so that the most recent orders are listed first

22 İndex  CREATE CLUSTERED INDEX Index_Name_Clstd ON Students(Name);  CREATE UNIQUE INDEX Index_Name_Unique ON Students (Name);  CREATE NONCLUSTERED INDEX Index_Name_NonClstd ON Students(Name);

23 . Rebuild / REORGANIZE index  ALTER INDEX PK_Employee_BusinessEntityID ON HumanResources.Employee REBUILD;  ALTER INDEX PK_ProductPhoto_ProductPhotoID ON Production.ProductPhoto REORGANIZE ;

24

25 XML Index  An XML index can be created on an XML column and the table must have a clustered index on the primary key. The XML index can be primary or secondary  CREATE TABLE MyTable (Col1 INT PRIMARY KEY, XmlCol XML)  CREATE PRIMARY XML INDEX idx_xCol_MyTable on MyTable (xCol)  CREATE XML INDEX PIdx_MyTable_XmlCol_PATH ON MyTable(XmlCol) USING XML INDEX PIdx_MyTable_XmlCol FOR PATH GO CREATE XML INDEX PIdx_MyTable_XmlCol_VALUE ON T(XmlCol) USING XML INDEX PIdx_MyTable_XmlCol FOR VALUE

26 Spatial Index  SQL Server 2008 provided a special type of column called a spatial column, which is a table column that contains data of a spatial data type, such as geometry or geography  CREATE TABLE MySpatialTable(id int primary key, geometry_col geometry);  CREATE SPATIAL INDEX SIndx_MySpatialTable_geometry_col1 ON MySpatialTable(geometry_col) WITH ( BOUNDING_BOX = ( 0, 0, 500, 200 ) );

27 Missing index should create that will help in improving the performance of queries  SELECT sys.objects.name, (avg_total_user_cost * avg_user_impact) * (user_seeks + user_scans) AS Impact, 'CREATE NONCLUSTERED INDEX ix_IndexName ON ' + sys.objects.name COLLATE DATABASE_DEFAULT + ' ( ' + IsNull(mid.equality_columns, '') + CASE WHEN mid.inequality_columns IS NULL THEN '' ELSE CASE WHEN mid.equality_columns IS NULL THEN '' ELSE ',' END + mid.inequality_columns END + ' ) ' + CASE WHEN mid.included_columns IS NULL THEN '' ELSE 'INCLUDE (' + mid.included_columns + ')' END + ';' AS CreateIndexStatement, mid.equality_columns, mid.inequality_columns, mid.included_columns FROM sys.dm_db_missing_index_group_stats AS migs INNER JOIN sys.dm_db_missing_index_groups AS mig ON migs.group_handle = mig.index_group_handle INNER JOIN sys.dm_db_missing_index_details AS mid ON mig.index_handle = mid.index_handle AND mid.database_id = DB_ID() INNER JOIN sys.objects WITH (nolock) ON mid.OBJECT_ID = sys.objects.OBJECT_ID WHERE (migs.group_handle IN ( SELECT TOP (500) group_handle FROM sys.dm_db_missing_index_group_stats WITH (nolock) ORDER BY (avg_total_user_cost * avg_user_impact) * (user_seeks + user_scans) DESC)) AND OBJECTPROPERTY(sys.objects.OBJECT_ID, 'isusertable')=1 ORDER BY 2 DESC, 3 DESC

28 Unused index the indexes that have not been used.  SELECT o.name, indexname=i.name, i.index_id, reads=user_seeks + user_scans + user_lookups, writes = user_updates, rows = (SELECT SUM(p.rows) FROM sys.partitions p WHERE p.index_id = s.index_id AND s.object_id = p.object_id), CASE WHEN s.user_updates 10000 ORDER BY reads


Download ppt "T-sql triger examples.  Öğrenci eklendiğinde mesaj veren triger CREATE TRIGGER trigAddStudents ON Students FOR INSERT AS VARCHAR(100)"

Similar presentations


Ads by Google