Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SAS - Break out of macro %DO loop

Tags:

sas

sas-macro

I know there exists the LEAVE statement for data step DO loops to terminate the current loop. I cannot find, however, documentation for a corresponding macro command.

I've tried %LEAVE but that appears not to be defined.

  1. Does SAS not have a break statement for macro loops?
  2. If not, are there other options beside using %GOTO or a DATA _NULL_?
like image 509
Lorem Ipsum Avatar asked Oct 20 '17 15:10

Lorem Ipsum


2 Answers

I generally use a %GOTO for breaking out of a macro loop, if a %RETURN statement is not an option. And I sometimes also use a GOTO for leaving a datastep loop, because: the most CPU-efficient way of programming depends on being able to leave not just the current loop, but the loop surrounding that as well.

Until you can specify the level of loop that you want to break out of, there is no way around the occasional GOTO if you want to program with maximal efficiency and clarity. And this is true for SAS, C, C++ and any other language that uses loop constructs. Without GOTO you will have to do silly stuff like repeating code and checking for the same condition more than once.

like image 124
Søren Lassen Avatar answered Oct 09 '22 17:10

Søren Lassen


If you want to break out of a macro completely, you can use %abort (if you want to trigger an error) or %return (if you don't). These won't help if you just want to break out of a loop and carry on with the rest of your macro, but you could potentially write a loop as a separate macro and call it inside a larger macro.

Another option is to use %do %while or %do %until and check your exit condition at the start of each loop, with extra %if-%then-%do-%end blocks based on the same condition within the loop if you want to skip the rest of an iteration after a break condition is met halfway through.

like image 39
user667489 Avatar answered Oct 09 '22 18:10

user667489