I have a table called Position that has a structure similar to the following:
PositionID - unique key
PersonnelID - foreign key
Company
Start Date
End Date
Address1
City
etc etc etc
When a new row is inserted, I want to compare it to the previous row for the same personnel ID, and then send an email listing only what has changed. This is all working now, but it seems very clunky the way I've done it, and I would like to know if there is a way to streamline it.
What I've done is declared a variable for every field in the table... twice. E.g. I have @newStartDate and @oldStartDate. Then I select values into each of those variables using something similar to
select @newStartDate = StartDate, @newEndDate = EndDate, [etc] where PositionID = @NewID
Then I go through a huge block of
if @newStartDate <> @oldStartDate
select @msg = @msg + 'Start Date changed from' + @oldStartDate + ' to ' + @newStartDate
(My code has all the proper casts and checks for nulls, I'm just simplifying)
At the end of everything, if @msg isn't blank, I send an email to the appropriate people.
ANYWAY... is there a way in T-SQL (using Microsoft SQL Server 8 currently, about to transition over to SQL 2005 which is why I'm looking at this now) to do this more efficiently? I thought about having only two variables (@newVal and @oldVal) and doing a select for each pair of values, but decided that saved on variables, but was way less efficient!)
Thank you for any direction/suggestions you can provide!
PositionID - unique key
PersonnelID - foreign key
Company
Start Date
End Date
Address1
City
etc etc etc
When a new row is inserted, I want to compare it to the previous row for the same personnel ID, and then send an email listing only what has changed. This is all working now, but it seems very clunky the way I've done it, and I would like to know if there is a way to streamline it.
What I've done is declared a variable for every field in the table... twice. E.g. I have @newStartDate and @oldStartDate. Then I select values into each of those variables using something similar to
select @newStartDate = StartDate, @newEndDate = EndDate, [etc] where PositionID = @NewID
Then I go through a huge block of
if @newStartDate <> @oldStartDate
select @msg = @msg + 'Start Date changed from' + @oldStartDate + ' to ' + @newStartDate
(My code has all the proper casts and checks for nulls, I'm just simplifying)
At the end of everything, if @msg isn't blank, I send an email to the appropriate people.
ANYWAY... is there a way in T-SQL (using Microsoft SQL Server 8 currently, about to transition over to SQL 2005 which is why I'm looking at this now) to do this more efficiently? I thought about having only two variables (@newVal and @oldVal) and doing a select for each pair of values, but decided that saved on variables, but was way less efficient!)
Thank you for any direction/suggestions you can provide!