我有一个存储过程,该过程应该处理某一天的数据并填写历史记录表。但是,如果该天的数据已经处理过,即,如果历史记录表中该日期的任何一行,它都将中止:
SET XACT_ABORT ON;
IF EXISTS (
select *
from history_table
where convert(date, call_time) = @date_to_process
)
THROW 50000, N'This day has already been processed. Exiting!', 1;
// process the data ...
// fill the history table
insert into history_table (call_time, other_data)
select call_time, other_data
from #processed_data;
有时,我用肯定没有经过处理的@date_to_process
调用SP时,仍然出现错误“ 这一天已经处理完毕。正在退出!”。但是,当我查看历史记录表时,发现插入语句实际上已运行。我怀疑这两个语句是按顺序运行的。看来INSERT语句在存在检查之前之前完成。
我如何确保它们按顺序运行?
答案 0 :(得分:0)
看起来您只需要使用ELSE
即可执行一条语句:
SET XACT_ABORT ON;
IF EXISTS (select null
from history_table
where convert(date, call_time) = @date_to_process
)
THROW 50000, N'This day has already been processed. Exiting!', 1;
ELSE // fill the history table
insert into history_table (call_time, other_data)
select call_time, other_data
from #processed_data;