sqlcmd goto isn't quite working—ends script on error
-
21-09-2019 - |
Question
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;
Solution
you start sqlcmd with the -b
on error batch abort option to stop on error.
OTHER TIPS
If you want a non-zero return value you can return the value in @intErrorCode
ala
RETURN @intErrorCode
Selecting it returns it in a result set rather than return value.
try using try-catch:
DECLARE @intErrorCode INT
BEGIN TRY
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')
SET IDENTITY_INSERT dbo.SomeTable OFF
UPDATE dbo.SomeTable
SET some_type = 'Contract Analytical'
WHERE some_type_id = 2
END TRY
BEGIN CATCH
IF XACT_STATE()!=0
BEGIN
ROLLBACK TRANSACTION
END
SELECT
,ERROR_NUMBER() AS ErrorNumber --same as @@ERROR
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage
PRINT 'Unexpected error occurred!'
RETURN 999
END CATCH
COMMIT TRAN T1;
RETURN 0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow