Chr*_*s L 8 sql-server stored-procedures sql-server-2008
我有一个sql脚本设置为滚动到生产.我把各种项目包装成单独的交易.在我们创建存储过程的每个事务中.我收到错误消息
消息156,级别15,状态1,行4关键字"过程"附近的语法不正确.
我创建了这个示例脚本来说明
Begin Try
Begin Transaction
-- do a bunch of add/alter tables here
-- do a bunch of data manipulation/population here
-- create a stored proc
create procedure dbo.test
as
begin
select * from some_table
end
Commit
End Try
Begin Catch
Rollback
Declare @Msg nvarchar(max)
Select @Msg=Error_Message();
RaisError('Error Occured: %s', 20, 101,@Msg) With Log;
End Catch
Run Code Online (Sandbox Code Playgroud)
这个错误似乎意味着我无法在事务中创建存储过程,但我找不到任何其他说明的文档(也许google今天不是freindly).
KM.*_*KM. 12
尝试做create procedure的EXEC('...'),就像这样:
Begin Try
Begin Transaction
-- do a bunch of add/alter tables here
-- do a bunch of data manipulation/population here
-- create a stored proc
EXEC ('create procedure dbo.test
as
begin
select * from some_table
end')
Commit
End Try
Begin Catch
Rollback
Declare @Msg nvarchar(max)
Select @Msg=Error_Message();
RaisError('Error Occured: %s', 20, 101,@Msg) With Log;
End Catch
GO
Run Code Online (Sandbox Code Playgroud)
Tho*_*mas 11
您无法以这种方式编写脚本,因为必须在自己的批处理中运行许多语句.相反,我建议做一些类似于Red-Gate的SQL Compare如何构建其脚本的东西:
Set Xact_Abort On
GO
Begin Transaction
GO
If object_id('tempdb..#tmpErrors') is not null
Drop Table #tmpErrors
GO
Create Table #tmpErrors( [Error] int not null )
GO
Create Procedure dbo.Test
As
Begin
--....
End
GO
If @@Error <> 0 AND @@TranCount >0 Rollback Transaction
GO
IF @@TranCount = 0 Begin Insert #tmpErrors (Error) Select 1 Begin Transaction End
GO
-- more statements
GO
If @@Error <> 0 AND @@TranCount >0 Rollback Transaction
GO
IF @@TranCount = 0 Begin Insert #tmpErrors (Error) Select 1 Begin Transaction End
GO
--.....
IF NOT EXISTS(SELECT * FROM #tmpErrors)
BEGIN
PRINT 'The database update succeeded'
IF @@TRANCOUNT > 0 COMMIT TRANSACTION
END
ELSE
BEGIN
PRINT 'The database update failed'
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION
END
GO
DROP TABLE #tmpErrors
GO
Run Code Online (Sandbox Code Playgroud)