This is the first time i’ve used IF Exists and BEGIN TRANSACTION. I get an error on ‘incorrect syntax near ‘)’ in the If Exists part and incorrect syntax near ‘Transaction’ at the end of End Transaction. What I’m trying todo is raise an error if a duplicate Entry exists and if there is an error rollback the transaction and return the error or return @@RowCount i don’t know which one I should choose could someone correct my procedure and make any adjustments on it please.
BEGIN TRANSACTION
IF EXISTS (SELECT * FROM Forums WHERE Title = @Title)
BEGIN
RAISERROR ('Duplicate Entry', 16, 1)
END
ELSE
BEGIN
INSERT INTO Forums(AddedBy, AddedDate, Title, Description,
ParentID, Moderated, ImageUrl, UpdatedBy, UpdatedDate, Active, Importance)
VALUES(@AddedBy, @AddedDate, @Title, null, null, False, null, null, null, True, 0)
RETURN @@ROWCOUNT
END
IF @@ERROR <> 0
BEGIN
ROLLBACK TRANSACTION
RETURN @@ERROR
END
END TRANSACTION
You don’t need a transaction unless you wanna enforce an isolation level, or if you have more than one Update/Insert/Delete statement, and you need to roll them all back if an error happens, or commit them all if everything is successful,
in your sample code, you have an insert statement that won’t even get to execute, so you have nothing to rollback