我认为msdn https://msdn.microsoft.com/en-CA/library/ms181271.aspx中对BREAK的描述就在我身边.但是我在通过调试单步执行时会遇到一些奇怪的行为.我说奇怪,因为它不一致.有时它会逃到我期望的层……有时它会跳过一对.
WHILE ... BEGIN stuff1 IF...BEGIN stuff2 WHILE ... BEGIN stuff3 IF .... BEGIN stuff4 IF @NumberRecords=0 BREAK stuff5 END --stuff6 if @NumberRecords=0 and @loopBOMRowCount=@ResultsSOloopstart-1 break --on the last occasion I observed,@loopBOMRowCount was 6 and @ResultsSOloopstart 71 and it never highlighted this section,either way SET @loopBOMRowCount = @loopBOMRowCount + 1 END stuff7 --nothing actually here END --stuff8 SET @periodloopcount=@periodloopcount+1 --this is where it ended up highlighting on that last occasion END stuff9
所以如果NumberRecords = 0,那么下一个op应该是if在stuff6,对吗?即使stuff4包含,例如,EXEC调用存储过程的INSERT INTO表?没有什么能够将堆栈混淆出层?
是的,我意识到这是丑陋的sql.大多数指令都是在两个临时表上进行编辑的,我避免将它们来回传递给存储过程,否则这些存储过程会清理代码.
编辑
我设法通过在内部IF周围添加一个虚拟WHILE循环来让它按照我想要的方式进行路由.但我真的很想知道我是如何误解msdn信息的.似乎BREAK应该突破IF,只要它有一个END语句.
退出WHILE语句中的最内层循环或WHILE循环内的IF … ELSE语句.将执行END关键字之后出现的任何语句,标记循环的结束.
解决方法
Exits the innermost loop in a WHILE statement or an IF…ELSE statement
inside a WHILE loop. Any statements appearing after the END keyword,
marking the end of the loop,are executed. BREAK is frequently,but
not always,started by an IF test.
然而事实并非如此. BREAK从其位置退出最内部的WHILE.文档的关键部分是“在END关键字之后出现的任何语句,标记循环结束,都会被执行.”
这个例子证明了这一点
例1
DECLARE @X INT = 1; PRINT 'Start' /* WHILE loop required to use BREAK. */ WHILE @X = 1 BEGIN /* Outer IF. */ IF 1 = 1 BEGIN /* Inner IF. */ IF 2 = 2 BEGIN BREAK PRINT '2' END PRINT '1' END SET @X = @X + 1; END PRINT 'End'
仅打印“开始”和“结束”文本.因为BREAK存在WHILE,所以不打印1.
您还可以在此处看到此行为:
例2
/* Anti-Pattern. * Breaking outside a WHILE is not allowed. */ IF 1 = 1 BEGIN BREAK PRINT 1 END
Msg 135,Level 15,State 1,Line 4 Cannot use a BREAK statement outside the scope of a WHILE statement.