I am trying to learn how to use transactions and error handling. Got stuck with custom error messages.
The stored procedure generates badges for AdventureWorks employees. The rule is for each employee to have only one valid badge at a time. If a badge is lost, a new badge is issued while the old badge is invalidated. This part of a code seems to work well so far.
Where I really got stuck was generating an error message advising that no badge was issued when an invalid employee ID is entered.
Also, just need a second opinion. I tried to set @@TRANSCOUNT
and ROLLBACK TRANSACTION
to make sure it does not mess with existing badges (e.g. invaliding a badge while not issuing a new one). But, I have a feeling that it is really not needed in this procedure. What do you think?
CREATE PROCEDURE dbo.spIssueNewID
@EmpID INTEGER
AS
BEGIN TRY
BEGIN TRANSACTION
UPDATE dbo.Badges
SET Validity = 'N'
WHERE EmpID = @EmpID;
INSERT INTO dbo.Badges (EmpID, EmpName, EmpLastName)
SELECT BusinessEntityID, FirstName, LastName
FROM AdventureWorks2016_EXT.person.person
WHERE BusinessEntityID = @EmpID;
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF @@ROWCOUNT = 0
BEGIN
PRINT 'No ID was issued'
END;
IF @@TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION
END
PRINT ERROR_MESSAGE();
THROW 50001,'An error occurred',0;
END CATCH;
Also, just in case if you need it for more context, presented below is dbo.Badges
that I've created:
CREATE TABLE dbo.Badges
(
ID uniqueidentifier NOT NULL DEFAULT NEWID(),
EmpID INTEGER NOT NULL
REFERENCES Person.Person (BusinessEntityID),
EmpName nvarchar(50) NOT NULL,
EmpLastName nvarchar(50) NOT NULL,
IssueDate date DEFAULT GETDATE(),
Validity char(1) DEFAULT 'Y',
CONSTRAINT ID_status CHECK (Validity IN ('Y', 'N'))
);