I'm using SQL Server 2014.
EDIT: I guess I should have been more clear. I do understand that by placing everything in a TRY/CATCH, that it will perform how I am wanting it to perform. For this question, I'm mostly just asking if the first example is bad practice, and if there is a way to throw an error that causes termination without the use of RETURN or a TRY/CATCH block. And after looking at the current answers, and linked documentation, I think the answer is...yes it's bad practice, and no you can't terminate with a failure using ONLY the THROW function.
I've written a proc where I would like to have a couple of pre-checks before the remainder of the code runs. An example would be, I have a service that runs for certain customers, and a table controls which customers it should run for, and a different table that controls whether that service itself is enabled.
Here's an example I just threw together. It checks to make sure that service is enabled, and it also makes sure the service is enabled for that specific customer. If not, the proc exits with an error. And also hopefully returning a failure to any job potentially running this proc.
I don't have a lot of experience with THROW or TRY/CATCH, but I just want to make sure I'm not missing something here. I found that THROW does not terminate the proc unless it is in a TRY block. So since I am using THROW outside of a TRY am I correctly using it by also using a RETURN after the THROW?
DECLARE @CustomerID INT = 10000 --Proc Parameter
DECLARE @ServiceID INT = 1
IF NOT EXISTS (SELECT * FROM dbo.Service WHERE ServiceID = @ServiceID AND [Enabled] = 1)
BEGIN
;THROW 51000, 'Service is not enabled', 1;
RETURN;
END
IF NOT EXISTS (SELECT * FROM dbo.CustomerService WHERE CustomerID = @CustomerID AND ServiceID = @ServiceID AND [Enabled] = 1)
BEGIN
;THROW 51000, 'Customer does not have service enabled', 1;
RETURN;
END
--Do stuff
Side Note: I'm really just asking if I'm using THROW incorrectly in this way, or if there is a way to use THROW where it will cause a failure/return.
EDIT/UPDATE: I suppose I could write it like this, not sure if that's an odd way to write SQL though.
DECLARE @CustomerID INT = 10000 --Proc Parameter
DECLARE @ServiceID INT = 1
BEGIN TRY
IF NOT EXISTS (SELECT * FROM dbo.Service WHERE ServiceID = @ServiceID AND [Enabled] = 1)
THROW 51000, 'Service is not enabled', 1;
IF NOT EXISTS (SELECT * FROM dbo.CustomerService WHERE CustomerID = @CustomerID AND ServiceID = @ServiceID AND [Enabled] = 1)
THROW 51000, 'Customer does not have service enabled', 1;
END TRY
BEGIN CATCH
THROW;
END CATCH
--Do Stuff