SQL管理器if语句和try / catch语句

时间:2018-12-13 18:31:00

标签: sql-server tsql

现在我有3个if语句,下面几乎都一样,我一直在寻找一种将所有3个语句组合在一起的方法,因此如果有人对如何进行操作有任何建议,我将在很长一段时间内将它们分开3个非常感谢。如果在sql err中为什么不能放其他

  IF (@updateTerm = 1)
  BEGIN
    update odb.transcriptCourse
    set startTerm = 1, endTerm = 1, actualTerm = 1, calendarTerms = 1
    where endyear = @fiscalYear
        and actualTerm = 2
        and schoolNumber in('0150', '0840', '0360')
        and (startTerm != 1 or  endTerm != 1 or actualTerm != 1 or 
    calendarTerms != 1)   END
  ELSE
  BEGIN
    PRINT 'This is not term 1';
  END

  IF (@updateTerm = 2)
  BEGIN
    update odb.transcriptCourse
    set startTerm = 2, endTerm = 2, actualTerm = 2, calendarTerms = 2
    where endyear = @fiscalYear
       and actualTerm = 4
       and schoolNumber in('0150', '0840', '0360')
       and (startTerm != 2 or  endTerm != 2 or actualTerm != 2 or 
    calendarTerms != 2)   END
  ELSE
  BEGIN
    PRINT 'This is not term 2';
  END

  IF (@updateTerm = 7)
  BEGIN
    update odb.transcriptCourse
    set startTerm = 7, endTerm = 7, actualTerm = 7, calendarTerms = 1
    where endyear = @fiscalYear
        and schoolname like 'Z %'
        and (startTerm != 7 or  endTerm != 7 or actualTerm != 7 or 
    calendarTerms != 1)END
  ELSE
  BEGIN
    PRINT 'This is not term 7';
  END

1 个答案:

答案 0 :(得分:0)

update odb.transcriptCourse
set startTerm = @updateTerm, endTerm =  @updateTerm, actualTerm =  @updateTerm, calendarTerms = case WHEN @updateTerms = 7 then 1 else @updateTerms end
where  1 = 1 AND (
(@updateTerm = 1 AND (endyear = @fiscalYear
and actualTerm = 2
and schoolNumber in('0150', '0840', '0360')
and (startTerm != 1 or  endTerm != 1 or actualTerm != 1 or 
calendarTerms != 1))  )
OR
( @updateTerm = 2 AND ( endyear = @fiscalYear
and actualTerm = 4
and schoolNumber in('0150', '0840', '0360')
and (startTerm != 2 or  endTerm != 2 or actualTerm != 2 or 
calendarTerms != 2)))
OR
(@updateTerm =3 AND (where endyear = @fiscalYear
and schoolname like 'Z %'
and (startTerm != 7 or  endTerm != 7 or actualTerm != 7 or 
calendarTerms != 1))))

短路逻辑ov @updateterm = x将处理单独的if语句