tracking_table
是一个声明如下的日志表:
create table tracking_table (my_command nvarchar(500), my_date datetime);
请假设您在SQL Server 2005作业中声明了以下SQL SERVER 2005代码块:
DECLARE @my_statement NVARCHAR(500)
delete from tracking_table
SET @my_statement = 'ALTER INDEX ALL ON my_user.dbo.my_fact_table REBUILD WITH (FILLFACTOR = 90)'
insert into tracking_table values (@my_statement,getdate())
EXEC (@my_statement)
SET @my_statement = 'ALTER INDEX ALL ON my_user.dbo.my_second_table REBUILD WITH (FILLFACTOR = 90)'
insert into tracking_table (@my_statement,getdate())
EXEC (@my_statement)
在运行时,如果第一个语句(ALTER INDEX ALL ON my_user.dbo.my_fact_table REBUILD WITH (FILLFACTOR=90)
)失败,则不会执行作用于my_second表的第二个语句。
我想知道如何修改SQL Server 2005代码,以便跳过任何错误,继续(在Oracle中我会说,WHEN OTHERS THEN NULL
)。
我怎么能实现这个目标?
提前感谢您的帮助。
答案 0 :(得分:2)
我不能建议压制错误,但如果你真的想这样做,我想你可以试试:
declare @my_statement nvarchar(500)
begin try
delete from tracking_table
end try
begin catch
print null // or errormessage
end catch
begin try
set @my_statement = 'ALTER INDEX ALL ON my_user.dbo.my_fact_table REBUILD WITH (FILLFACTOR = 90)'
insert into tracking_table values (@my_statement,getdate())
exec (@my_statement)
end try
begin catch
print null // or errormessage
end catch
begin try
set @my_statement = 'ALTER INDEX ALL ON my_user.dbo.my_second_table REBUILD WITH (FILLFACTOR = 90)'
insert into tracking_table (@my_statement,getdate())
exec (@my_statement)
end try
begin catch
print null // or errormessage
end catch
您也可以创建程序
create procedure sp_executesql_Suppress_Errors
(
@stmt nvarchar(max)
)
as
begin
begin try
exec sp_executesql
@stmt = @stmt
end try
begin catch
print null // or errormessage
end catch
end
然后用你的陈述来调用它。我还建议您使用exec sp_executesql
代替exec
(请参阅Dynamic SQL - EXEC(@SQL) versus EXEC SP_EXECUTESQL(@SQL))