Microsoft SQL Server 2005
Database Design Best Practices

How to maintain computed column with trigger?

 

Execute the following script in Query Editor to demonstrate the maintenance of a computed column with a trigger. InventoryListValue is the trigger computed column. Computed values are actually stored in an indexable column.

USE tempdb
GO

CREATE TABLE dbo.Product (
ProductID int identity(1,1) primary key
, ProductName char(30)
, QtyOnHand int
, UnitPrice money
, InventoryListValue money
)
GO

IF EXISTS (SELECT 1 FROM sys.objects o
JOIN sys.schemas s
ON s.schema_id = s.schema_id
WHERE o.name = 'trgListValue' AND o.type = 'TR' and s.name='dbo')
DROP TRIGGER dbo.trgListValue;
GO

CREATE TRIGGER dbo.trgListValue
ON dbo.Product
AFTER INSERT, UPDATE
AS
IF ( UPDATE (QtyOnHand) OR UPDATE (UnitPrice) )
BEGIN
UPDATE p SET p.InventoryListValue=i.QtyOnHand * i.UnitPrice
FROM dbo.Product p
JOIN inserted i
on p.ProductID=i.ProductID
END;
GO

INSERT dbo.Product(ProductName, QtyOnHand, UnitPrice) SELECT 'Ipod', 25, 300
INSERT dbo.Product(ProductName, QtyOnHand, UnitPrice) SELECT 'Iphone', 99, 500
INSERT dbo.Product(ProductName, QtyOnHand, UnitPrice) SELECT 'Dell laptop', 10, 900
GO

SELECT * from dbo.Product
GO

UPDATE dbo.Product SET UnitPrice = 295 WHERE ProductName='Ipod'
GO

SELECT * from dbo.Product
GO

 

The Best SQL Server 2005 Training in the World
 
 
SQLUSA.com Home Page