Search code examples
sasenterprise-guide

SAS: Conditional choice of library


I have the same table name in two different libraries, and I want to use a condition in the beginning to choose what library to use (SAS Enterprise Guide). Is it possible to use a variable for the library to achieve something like below?

IF(txt = 'tst")

Select * from TST.TableName

ELSE

Select * form DEV.TableName


Solution

  • The best way to do this varies based on what defines txt. If you are choosing this based on user input (in your example, user chooses TEST or DEV (or PROD) database to point to), then the best way in Enterprise Guide is to create a prompt to create a macro variable, or secondarily directly create a macro variable.

    Ben Cochran's paper Be Prompt Now: Creating and Using Prompts in SAS Enterprise Guide is a good introduction to the topic, as well as other sources online. You can set up a prompt that asks the user which environment to point to, and then it will define a macro variable with a value of your choosing. Then add the prompt to the program that you need it to be related to, and presto, it works.

    So in your case, you could have it set a variable &env. that contains the value of the table name (TST or DEV). You could also have it control the libname value itself (so you don't change which libname is used, but you instead change which folder or database the libname points to).


    If you're not in EG, or if you don't want to use a prompt for this for whatever reason, you similarly can assign that macro variable yourself.

    %let env = TST;
    

    Either way, once you've got &ENV=TST established, you just use it in open code:

    proc sql;
      select * from &ENV..TableName;
    quit;
    

    Or, like I said, you could assign the libname based on the macro variable and use a single libname in code; that's often cleaner, though it leaves its own complications.