我正在使用带有SQL Server的sqlcmd工具来执行脚本。脚本添加/更新记录。如果脚本抛出错误,我需要sqlcmd停止执行并给出非0返回值。我认为以下内容可行,但事实并非如此。
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;
答案 0 :(得分:2)
使用-b
on error batch abort选项启动sqlcmd以便在出错时停止。
答案 1 :(得分:0)
如果需要非零返回值,可以返回@intErrorCode
中的值ala
RETURN @intErrorCode
选择它会在结果集中返回,而不是返回值。
答案 2 :(得分:0)
尝试使用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