I am using the sqlcmd tool with SQL Server to execute scripts. The scripts add/update records. I need sqlcmd to stop executing and give a non 0 return value if the script throws an error. I thought the following would work but it does not.
DECLARE @intErrorCode INT
BEGIN TRAN T1;
SET IDENTITY_INSERT dbo.SomeTable ON
INSERT INTO dbo.SomeTable(some_type_id,some_type,code_definition,use_some_lookup,created_by,created_on,modified_by,modified_on,org_some)
VALUES(0,'yadayada','None','N','system',GETDATE(),'system',GETDATE(),'N')
SELECT @intErrorCode = @@ERROR
IF (@intErrorCode <> 0) GOTO PROBLEM
SET IDENTITY_INSERT dbo.SomeTable OFF
UPDATE dbo.SomeTable
SET some_type = 'Contract Analytical'
WHERE some_type_id = 2
SELECT @intErrorCode = @@ERROR
IF (@intErrorCode <> 0) GOTO PROBLEM
PROBLEM:
IF (@intErrorCode <> 0) BEGIN
PRINT 'Unexpected error occurred!'
ROLLBACK TRAN
SELECT @intErrorCode
RETURN
END
COMMIT TRAN T1;