代码之家  ›  专栏  ›  技术社区  ›  ercan

如何避免在存储过程中并行执行

  •  0
  • ercan  · 技术社区  · 5 年前

    我有一个存储过程,它应该处理某一天的数据并填充历史记录表。但是,如果该天的数据已经被处理,即,如果历史记录表中的某个日期有任何一行,则应该中止:

    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 这肯定是以前没有处理过的,我仍然得到错误“ 这一天已经被处理了。正在退出! ". 但是当我查看历史记录表时,我看到insert语句实际上运行了。我怀疑这两种说法是否是连续的。INSERT语句似乎结束了 之前 存在性检查。

    1 回复  |  直到 5 年前
        1
  •  0
  •   iamdave    5 年前

    看起来你只需要使用 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;