Hi,
I need to extract records from a table, copy the data to a second table and then update the records in the first table to indicate that they have been copied across successfully.
My current SP code is this:
SELECT TBL_ADDRESSBOOKADDRESSES.* FROM TBL_ADDRESSBOOKADDRESSES
INNER JOIN TBL_CAMPAIGNS
ON TBL_ADDRESSBOOKADDRESSES.adds_ABMId = TBL_CAMPAIGNS.campaign_AddressBook
WHERE TBL_CAMPAIGNS.campaign_Status = 1
Now once the above is performed i need to insert this data into a second table called TBL_RECIPIENTS. Assume that the columns are simply named col_1, col_2, col_3 .... col_5 in TBL_ADDRESSBOOKADDRESSES and that this is the same in TBL_RECIPIENTS.
Once this action is performed i need to update TBL_CAMPAIGNS.campaign_Status = 2 Ideally this should only be for those records that have actually been updated(in case script gets stopped mid way through due to server crash etc)
Please let me know if you need anything clarifying.
Many Thanks!
Ive taken the advise kindly given below and come up with the working code below. Ive read tutorial which suggested adding try/catch to ensure rollback if any errors occurr. Is my code below adequate in this respect??
Any suggest would be gratefully received.
Thanks.
CREATE PROCEDURE web.SERVER_create_email_recipients
AS
BEGIN TRY
--sets (n) campaigns ready for transfer of emails to mailing list
UPDATE TOP(1) TBL_CAMPAIGNS
SET TBL_CAMPAIGNS.campaign_Status = 1
WHERE TBL_CAMPAIGNS.campaign_Status = 0
--finds above marked campaigns, retreives addresses then copies them to TBL_CAMPAIGNRECIPIENTS ready for auto mailout
INSERT TBL_CAMPAIGNRECIPIENTS (recip_CampaignId, recip_Email, recip_Forename, recip_Surname, recip_adds_Key)
SELECT C.Campaign_AddressBook, ABA.adds_Email, ABA.adds_RecipientForename, ABA.adds_RecipientSurname, ABA.adds_Key
FROM TBL_ADDRESSBOOKADDRESSES ABA
JOIN TBL_CAMPAIGNS C ON ABA.adds_ABMId = C.campaign_AddressBook
WHERE C.campaign_Status = 1
--checks that above emails have been copied across and then sets the campaigns status accordingly
UPDATE C
SET C.campaign_Status = 2
From TBL_CAMPAIGNS C
JOIN TBL_ADDRESSBOOKADDRESSES aba
ON aba.adds_ABMId = C.campaign_AddressBook
JOIN TBL_CAMPAIGNRECIPIENTS r on aba.adds_Key = r.recip_adds_Key
WHERE C.campaign_Status = 1
END TRY
BEGIN CATCH
-- Whoops, there was an error
IF @@TRANCOUNT > 0
ROLLBACK
-- Raise an error with the details of the exception
DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int
SELECT @ErrMsg = ERROR_MESSAGE(),
@ErrSeverity = ERROR_SEVERITY()
--throws out error to logs?
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH