Search code examples
syntaxerror-handlingtry-catchspss

Force an error in SPSS Syntax when condition is met


I'm doing a check in my syntax to see if all of the string fields have values. This looks something like this:

IF(STRING ~= "").

Now, instead of filtering or computing a variable, I would like to force an error if there are fields with no values. I'm running a lot of these scripts and I don't want to keep checking the datasets manually. Instead, I just want to receive an error and stop execution.

Is this possible in SPSS Syntax?


Solution

  • First, you can efficiently count the blanks in your string variables with COUNT:

    COUNT blanks = A B C(" ").

    where you list the string variables to be checked. So if the sum of blanks is > 0, you want the error to be raised. First aggregate to a new dataset and activate it:

    DATASET DECLARE sum.
    AGGREGATE /OUTFILE=sum /count=sum(blanks).

    The hard part is getting the job to stop when the blank count is greater than 0. You can put the job in a syntax file and run it using INSERT with ERROR=STOP, or you can run it as a production job via Utilities or via the -production flag on the command line of an spj (production facility) job.

    Here is how to generate an error on a condition.

    DATASET ACTIVATE sum.
    begin program.
    import spssdata
    
    curs = spssdata.Spssdata()
    count = curs.fetchone()
    curs.CClose()
    
    if count[0] > 0:
        spss.Submit("blank values exist")
    end program.
    DATASET CLOSE sum.
    

    This code reads the aggregate file and if the blank count is positive issues an invalid command causing an error, which stops the job.