sqlcmd goto 不太工作—结束脚本错误
我正在使用 sqlcmd 工具和 SQL Server 来执行脚本。脚本添加/更新记录。如果脚本抛出错误,我需要 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;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在错误批量中止时使用
-b
启动 sqlcmd 错误时停止的选项。you start sqlcmd with the
-b
on error batch abort option to stop on error.如果您想要一个非零返回值,您可以在 @intErrorCode
ala
中返回该值,选择它会在结果集中返回该值而不是返回值。
If you want a non-zero return value you can return the value in @intErrorCode
ala
Selecting it returns it in a result set rather than return value.
尝试使用 try-catch:
try using try-catch: