Data Validation with a SQL Trigger

For our semester long project for my SQL class, we had to create an actual database and we have been entering data and creating everything from views to scripts to triggers.

My database is a hypothetical small library in Ghana, which has been funded by a donor organization with a large number of books and several computers.  My own modest collection of 800+ books serves as the actual library (I haven’t entered them all in…yet).  The trigger I wrote is for when there is a fine to be paid.  The trigger will validate the data entered in.  Here’s the code.  Creative Commons License, and all that.

CREATE TRIGGER FineTableUpdate
ON Fines
INSTEAD OF INSERT, UPDATE
AS
DECLARE @PatronNo int, @BookNo int, @BookTitle varchar(50), @BorrowedDate Date,
@FineAmount money, @PaidStatus char(2), @TestRowCount int;
SELECT @TestRowCount = COUNT(*) FROM inserted;
IF @TestRowCount = 1
BEGIN
SELECT @PatronNo = Patron_ID, @BookNo = Book_ID, @PaidStatus = PaidStatus
FROM inserted;
BEGIN
IF NOT EXISTS (SELECT * FROM Patrons WHERE Patron_ID = @PatronNo)
THROW 50001, ‘That Patron does not exist.’, 1;
IF @PatronNo IS NULL
THROW 50001, ‘Invalid Patron Number.’, 1;
IF NOT EXISTS (SELECT * FROM Books WHERE Book_ID = @BookNo)
THROW 50001, ‘That Book does not exist.’, 1;
IF @BookNo IS NULL
THROW 50001, ‘Invalid Book Number.’, 1;
SET @BookTitle = (SELECT BookTitle FROM Books WHERE @BookNo = Books.Book_ID)
SET @BorrowedDate = (SELECT Date_Borrowed FROM Lending
WHERE @PatronNo = Patron_ID AND
@BookNo = Book_ID);
SET @FineAmount = DATEDIFF(day, @BorrowedDate, GETDATE())
IF @PaidStatus <> ‘Y’ OR @PaidStatus <> ‘N’
THROW 50001, ‘Paid Status must be Y or N’, 1;

INSERT Fines
(Patron_ID, Book_ID, Book_Title, FineAmount, PaidStatus)
VALUES (@PatronNo, @BookNo, @BookTitle, @FineAmount, @PaidStatus);
END;
END;
ELSE
THROW 50027, ‘Limit INSERT to a single row.’, 1;

Advertisements

One thought on “Data Validation with a SQL Trigger

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s