T-sql triger examples. Öğrenci eklendiğinde mesaj veren triger CREATE TRIGGER trigAddStudents ON...
-
Upload
bernice-barbra-nash -
Category
Documents
-
view
220 -
download
1
Transcript of T-sql triger examples. Öğrenci eklendiğinde mesaj veren triger CREATE TRIGGER trigAddStudents ON...
T-sql triger examples
Öğrenci eklendiğinde mesaj veren trigerCREATE TRIGGER trigAddStudentsON StudentsFOR INSERT ASDECLARE @Newname VARCHAR(100)SELECT @Newname =(SELECT Name FROM INSERTED)PRINT 'THE STUDENT ' + @Newname + ' IS ADDED.';
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
Enable/DisableENABLE/
DISABLE TRIGGER trgName ON tblNAme
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).
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)
WITH CTE AS ( select CustomerId from inserted union select CustomerId from deleted)UPDATE CustomersSET Priority = ... -- we will complete here soonFROM Customers cINNER JOIN CTE ON CTE.CustomerId = c.CustomerId
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.
select CustomerId, SUM([Net Amount]) Totalfrom Salesinner join CTE on CTE.CustomerId = Sales.CustomerIdwhere Completed = 1group by Sales.CustomerId
SQL Code of SQL Trigger AFTER Insert, Update, Delete CREATE TRIGGER
dbo.Update_Customer_Priority ON dbo.SalesAFTER INSERT, UPDATE, DELETEAS
WITH CTE AS ( select CustomerId from inserted union select CustomerId from deleted)UPDATE CustomersSET Priority = case when t.Total < 10000 then 3 when t.Total between 10000 and 50000 then 2 when t.Total > 50000 then 1 when t.Total IS NULL then NULL
endFROM Customers cINNER JOIN CTE ON CTE.CustomerId = c.CustomerIdLEFT 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
insert into Customers select N'MS SQL Server Team', NULLinsert into Customers select N'MS Windows Team', NULLinsert into Customers select N'MS Internet Explorer Team', NULL
insert into Sales select 1, 5000, 1
insert into Sales select 2, 45000, 1
insert into Salesselect CustomerId, 7500, 1 from Customers
update Sales set Completed = 0
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.
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)
UPDATE Trigger
CREATE TRIGGER trgFillInMissingCouponRateON [dbo].StateTaxFreeBondFOR INSERT,UPDATEASBEGIN UPDATE StateTaxFreeBondArchive SET CouponRate = isnull(i.CouponRate,m.CouponRate) FROM StateTaxFreeBondArchive m INNER JOIN inserted i ON m.MBCID = i.MBCIDEND
Instead of trigger
Index yapısı
so that the most recent orders are listed first
İ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);
. Rebuild / REORGANIZE index
ALTER INDEX PK_Employee_BusinessEntityID ON HumanResources.EmployeeREBUILD;
ALTER INDEX PK_ProductPhoto_ProductPhotoID ON Production.ProductPhotoREORGANIZE ;
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_XmlColFOR PATHGOCREATE XML INDEX PIdx_MyTable_XmlCol_VALUE ON T(XmlCol)USING XML INDEX PIdx_MyTable_XmlColFOR VALUE
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 ) );
Missing indexshould 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
Unused indexthe 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), CASEWHEN s.user_updates < 1 THEN 100ELSE 1.00 * (s.user_seeks + s.user_scans + s.user_lookups) / s.user_updatesEND AS reads_per_write, 'DROP INDEX ' + QUOTENAME(i.name) + ' ON ' + QUOTENAME(c.name) + '.' + QUOTENAME(OBJECT_NAME(s.object_id)) as 'drop statement'FROM sys.dm_db_index_usage_stats s INNER JOIN sys.indexes i ON i.index_id = s.index_id AND s.object_id = i.object_id INNER JOIN sys.objects o on s.object_id = o.object_idINNER JOIN sys.schemas c on o.schema_id = c.schema_idWHERE OBJECTPROPERTY(s.object_id,'IsUserTable') = 1AND s.database_id = DB_ID() AND i.type_desc = 'nonclustered'AND i.is_primary_key = 0AND i.is_unique_constraint = 0AND (SELECT SUM(p.rows) FROM sys.partitions p WHERE p.index_id = s.index_id AND s.object_id = p.object_id) > 10000ORDER BY reads