I have a SQL Server 2008 database with two tables. The first table is called Department. The second table is called Ticket. These two tables are defined as follows:
Department
----------
ID
Name
TotalTickets
Ticket
------
ID
DepartmentID
Description
AssignedTo
I’m trying to figure out a way to dynamically update the Department.TotalTickets value. When a Ticket gets added or removed, I want to automatically increment or decrement the value of the TotalTickets. Can someone please tell me the best way to do this on SQL Server 2008?
Thank you
There are a number of ways to achieve this, you can use triggers after insert or delete on your ticket table, or you could take
TotalTicketsout of department and put it in a view.If performance is an issue you can create the view as a indexed view, as Thomas points out the join would need to be an
INNER JOIN, table names would need to be in the formatdbo.Departmentand you would have to create the viewWITH SCHEMABINDINGto go down this route.The view will be updated as the tickets are inserted/deleted.