You are on page 1of 70

Best place to work

SAS By Example Best place to bank

 Agenda

 SAS Informats & Formats

 Functions – String, pattern and date


 Utility Procedures
 Reporting procedures
 Macros
 Proc SQL
 Optimization and Automation
Best place to work

SAS Training – Informats & Formats Best place to bank

 Topics to be covered
 SAS Informats
 Numeric Informats
 Character Informats
 Date Informats
 SAS Formats
 Numeric Formats
 Character Formats
 Date Formats
Best place to work
SAS Informats & Formats Contd…. Best place to bank

 Informats & Formats


 Informats enables SAS system to interpret the inputted data correctly.
 Format enables the SAS system to display the data in formatted way.

RAW DATA SAS DATA OUTPUT

$1,000.00 1000.00 1,000.0000

6.89% 0.0689 6.9


Informats Formats

17MAR2001 15051 03/17/01

17/03/2001 15051 17/03/01


Best place to work

SAS Informats Best place to bank

DATA TEST1;
 Numeric Informats INPUT
AMT1 : 8.2 /* Tot length 8 digits with2 decimal places */
1. width. (8. 15. 32. ) AMT2 : COMMA8.2 /* To account for $ and embedded comma */
AMT3 : COMMAX8.2 /* Comma and period interchanging places */
2. width.decimal (8.2 15.2 32.5) PER1 : PERCENT4.2 /* To account for % symbol */
AMT4 : NUMX8.2 /* Decimal point replaced by comma */
3. Commawidth.decimal (comma32.2) ;
DATALINES;
4. CommaXwidth.decimal (commaX15.2) 1236.00 $1,000.00 $700.000,00 5.6% 850,00
1234.00 $2,500.00 $600.700,00 6.89% 680,78
5. NUMXwidth.decimal (NUMX8.2) 1236.78 $343.00 $800.800,00 17.56% 780,67
;
6. PERCENTwidth.decimal (PERCENT2.1) RUN;

Demonstration of Numeric Informat

Obs AMT1 AMT2 AMT3 PER1 AMT4

1 1236 1000.00 700000 0.05600 850.00


2 1234 2500.00 600700 0.06890 680.78

3 1236.78 343.00 800800 0.07560 780.67

4
Best place to work

SAS Informats Best place to bank

 Character Informats
DATA TEST2;
1. $width. ($50.) INPUT
STR1 : $10. /* Length of the string is 10 characters */
2. $upcasewidth. ($upcase3. ) STR2 : $UPCASE8. /* Up-casing the string */
STR3 : $REVERS5. /* Reading string in reverse order & trimming leading/trailing blanks */
3. $reverswidth. ($revers7. ) STR4 : $REVERJ5. /* Reading string in reverse order but NOT trimming blanks*/
;
4. $reverjwidth. ($reverj9. ) DATALINES;
Summary summary summary summary
;
RUN;

Demonstration of Character Informat

Obs STR1 STR2 STR3 STR4

1 Summary SUMMARY yrammuS yrammuS

5
Best place to work

SAS Informats Best place to bank

DATA TEST2;
 Date Informats: Part 1 INPUT
DATE1 : DATE9.
DATE2 : DDMMYY10. /* Notice the date separator “/” */
1. DATE9. (17MAR2010) DATE3 : DDMMYY10. /* Notice the date separator “:” */
DATE4 : DDMMYY10. /* Notice the date separator “-” */
2. DDMMYY10. (17/03/2001) DATE5 : DDMMYY10. /* Notice the date separator “.” */
DATE6 : JULIAN7.
3. JULIAN7. (2001077) ;
Other Variations DATALINES;
17MAR2001 17/03/2001 17:03:2001 17-03-2001 17.03.2001 2001077
1. MMDDYY10. 16MAR1985 16/03/1985 16:03:1985 16-03-1985 16.03.1985 1985076
;
2. YYMMDD10.
RUN;
3. YYDDMM10.

Demonstration of Date Informat Part 1

Obs DATE1 DATE2 DATE3 DATE4 DATE5 DATE6

1 15051 15051 15051 15051 15051 15052


2 9206 9206 9206 9206 9206 9207

6
Best place to work

SAS Informats Best place to bank

 DATA TEST3;
Date Informats: Part 2 INPUT
DATE1 : DATE7.
1. DATE7. (17MAR01) DATE2 : DDMMYY8. /* Date Separators can be “-” “.” “:” */
DATE3 : DATE11.
2. DATE11. (17-MAR-2001) DATE4 : MONYY5. /* Date value that corresponds to the 1 st day of the month */
DATE5 : YYMMN4. /* No separator permissible and day is 1st day of the month */
3. DDMMYY8.(17/03/01) DATE6 : JULIAN5.
;
4. MONYY5. (APR01) DATALINES;
17MAR01 17/03/01 17-MAR-2001 MAR01 0103 01077
5. JULIAN5.. (01077) 16MAR85 16/03/85 16-MAR-1985 MAR85 8503 85076
;
6. YYMMN4. (0103) RUN;
Other Variations
1. MONYY7.
2. YYMMN6.
3. DDMMYY6.
Demonstration of Date Informat Part 2
4. DDMMYY8. (No date
separator)
Obs DATE1 DATE2 DATE3 DATE4 DATE5 DATE6
5. WEEKVW. (YYY-Www-dd,
Year, week, day of week) 1 15051 15051 15051 15035 15035 15052
2 9206 9206 9206 9191 9191 9207
6. YYQ4. (85Q1)

7
Best place to work

SAS Formats Best place to bank

 Date Formats: The Regular Flavour


Date as stored in SAS DATA FOR1;
SET TEST3;
DATE1 DATE2 DATE3 DATE4 DATE5 DATE6
FORMAT DATE1 DDMMYY10.
15051 15051 15051 15035 15035 15052 DATE2 DDMMYYB8. /* Date separator is SPACE */
9206 9206 9206 9191 9191 9207 DATE3 DDMMYYC8. /* Date separator is COLON */
DATE4 DDMMYYP10. /* Date separator is PERIOD */
DATE5 MMDDYY10.
C = “COLON” DATE6 DATE9. ;
RUN;
D = “DASH”
P = “PERIOD”
S = “ FW SLASH”
B = “SPACE”
N = “No SEPARATOR”

DATE FORMATS

Obs DATE1 DATE2 DATE3 DATE4 DATE5 DATE6

1 17/03/2001 17 03 01 17:03:01 01.03.2001 03/01/2001 18MAR2001


2 16/03/1985 16 03 85 16:03:85 01.03.1985 03/01/1985 17MAR1985

8
Best place to work

SAS Formats Best place to bank

 Date Formats: The Not so Regular


DATA FOR2;
SET TEST3;
Date as stored in SAS
FORMAT DATE1 DOWNAME. /* Day of the week */
DATE1 DATE2 DATE3 DATE4 DATE5 DATE6 DATE2 DAY2. /* Day of the month */
DATE3 JULDAY3. /* Day of the year */
15051 15051 15051 15035 15035 15052 DATE4 MONNAME. /* Month of the date */
9206 9206 9206 9191 9191 9207 DATE5 MONYY. /* Month & Year */
DATE6 WEEKDAY1. /* Numeric day of the week */
;
RUN;

DATE FORMATS

Obs DATE1 DATE2 DATE3 DATE4 DATE5 DATE6

1 Saturday 17 76 March MAR01 1


2 Saturday 16 75 March MAR85 1

Few More!!!
1. WORDDATEw.
2. WORDDATXw.
3. YEARw.
4. YYQRw.

9
Best place to work

Functions Best place to bank

STRING MANIPULATIONS DATE FUNCTIONS


•Cat, Cats, Catt
•Compress •Making sense of SAS dates
•Verify •Date arithmetic
•Translate, Tranwrd •“Time travel”
•IFC IFN •Date formats/informats ref
PATTERN MATCHING •Date functions ref
•prxparse
•prxmatch References:
String functions:
•prxsubstr http://support.sas.com/publishing/pubcat/chaps/59343.pdf
Arrays:
ARRAY MANIPULATION http://www.lexjansen.com/cgi-bin/xsl_transform.php?x=tarr&s=sugi_t&c=sugi
http://support.sas.com/resources/papers/proceedings09/032-2009.pdf
•DIM
•Array Implementation
Best place to work

Best place to bank

String Manipulations

CAT CATS CATT


CAT Concatenates character strings without removing leading or trailing blank
CATS Concatenates character strings and removes leading and trailing blanks
CATT Concatenates character strings and removes trailing blanks

Using CAT Using CATS /


CATT
JOE J oe Joe
John J ohn John
pETE P ete Pete
RoberT R obert Robert
Best place to work

Best place to bank

String Manipulations Contd..

COMPRESS (char_value <, comp_string> <,modifiers>)


char_value is a SAS character value
comp_string is a character value containing the characters to remove from char_value
modifiers add additional characters to the list of characters to remove or modify the way the function works

Selected list of COMPRESS modifiers (upper- or lowercase)


A adds upper- and lowercase letters
D adds numerals (digits)
I ignores case
K keeps listed characters instead of removing them
S adds space (blank, tabs, line feed, carriage return) to the list
P adds punctuation
Before After
RBC=upcase(RBC); RBC=compress(RBC, '/','a');
RBC=compress(RBC,'ABCDEFGHIJKLMNOPQRSTUVWXYZ/');
RBCnum=input(RBC,10.);

12
Best place to work

Best place to bank

String Manipulations Contd..

Example

Data phone;
Input phone $15.;
Number = compress(phone,,'kd');

Datalines;
(908)235-4490
(201) 555-77 99
;
phone Number
(908)235-4490 9082354490
(201) 555-77 99 2015557799

13
Best place to work

Best place to bank

String Manipulations Contd..

Verify(String, Valid set)


String is the source string that is getting validated.

Valid set is the set of valid characters


Listing of Data Set VERIFY
id answer position
001 acbed 0
Data verify; 002 abxde 3
input @1 id $3. 003 12cce 1
@5 answer $5.; 004 abc e 4
position = verify(answer,'abcde');
datalines;
001 acbed
002 abxde
003 12cce
004 abc e
;
title "Listing of Data Set VERIFY";
proc print data=verify noobs;
run;

14
Best place to work

Best place to bank

String Manipulations Contd..

Translate and Tranwrd


Translate function replaces specific characters in a string with individual characters you specify,
returning an altered string

Tranwrd function replaces or removes all occurrences of a word in a string

Address=tranwrd(address,’Street’,’St.’);
Address=tranwrd(address,’Avenue’,’Ave.’);
Address=tranwrd(address,’Road’,’Rd.’);

Before After

Lazy Brook Road Lazy Brook Rd.


River Rd. River Rd.
Main Street Main St.

15
Best place to work

Best place to bank

String Manipulations Contd..

IFC & IFN:


IFC (condition, true, false, missing)
IFC function has four parameters:
a logical expression
character value returned when true
value returned when false
value returned when missing, which is optional

Before After

if vtype=1.4 then visit='Baseline';


else if vtype=1.5 then visit='Retreat'; visit=ifc(vtype=1.4,'Baseline','Retreat','Missing')
else if vtype=. then visit='Missing'; ;

NOTE: IFC & IFN have similar syntax. If vtype is numeric then we use IFN.

16
Best place to work

Best place to bank

Pattern Matching Using PERL


Why use Perl Regex in SAS?
Symbol Meaning E.G.
• PRX provides a very wide choice of
. Any character Any character
matching patterns based on a fairly
simple set of general principals \w Any word character a-z, A-Z, 0-9, $%&- etc

\d Any digit 0-9


• Can permit checking and substitutions
* Matches the previous \d* matches any number of digits,
that may otherwise require very large
expression 0 or more including zero
amounts of difficult to maintain code
times

+ Matches the previous \d+ matches one or more digits

expression 1 or more

times

\s White Space Spaces, tabs, carriage returns, etc

characters

17
Best place to work

Best place to bank

Pattern Matching

String Matching using PERL


John Smith
prxparse function is used to create a regular expression 12 Broad Street
Flemington, NJ 08822
prxsubstr function serves much the same purpose as the Philip Judson
Apt #1, Building 7
PRXMATCH function plus it returns the length of the match as 777 Route 730
well as the starting position Kerrville, TX 78028
Dr. Roger Alan
44 Commonwealth Ave.
***Primary functions: PRXPARSE and PRXSUBSTR Boston, MA 02116-7364
***Other functions: SUBSTRN; ;
DATA ZIPCODE;
IF _N_ = 1 THEN RE = PRXPARSE("/ \d{5}(-\d{4})?/");
RETAIN RE;
/* Match a blank followed by 5 digits followed by either nothing or a dash and 4 digits
\d{5} matches 5 digits - matches a dash \d{4} matches 4 digits
? matches zero of one of the preceding sub expression */ ZIP_CODE
INPUT STRING $80.; 08822
LENGTH ZIP_CODE $ 10; 78028
CALL PRXSUBSTR(RE,STRING,START,LENGTH); 02116-7364
IF START GT 0 THEN DO;
ZIP_CODE = SUBSTRN(STRING,START + 1,LENGTH - 1);
OUTPUT;
END;
KEEP ZIP_CODE;
Datalines;
Run;

18
Best place to work

Best place to bank

Pattern Matching Contd..

String Matching using PERL


PRXMATCH function Searches for a pattern match and
returns the position at which the pattern is found

12345678 02-9428044
1234 2-12345678
1234-45 02-1234
Data Work.PERL;
Input Id $ Phone $11. ;

Match1=Prxmatch("/\d{8}/",Id);
Match2=Prxmatch("/\d{2}(-\d{8})/",phone);

Datalines;
12345678 02-94280444 Match1 Match2
1234 2-12345678 1 1
; 0 0
Run; 0 0

Proc Print data=Work.PERL noobs;


Var Match1 Match2;
Run;

19
Best place to work

Best place to bank

Pattern Matching Contd..


Data CAT_AND_MOUSE;
String Matching using PERL Input TEXT $CHAR40.;
PRXCHANGE function substitute one string for another. Length NEW_TEXT $ 80;

Advantage of using PRXCHANGE over TRANWRD is that you can IF _N_ = 1 THEN MATCH = PRXPARSE("s/[Cc]at/Mouse/");
search for strings using wild cards. *Replace "Cat" or "cat" with Mouse;
Retain MATCH;

Syntax: CALL PRXCHANGE(pattern-id or regular-expression, times, CALL PRXCHANGE(MATCH,-1, TEXT, NEW_TEXT, R_LENGTH, TRUNC,
N_OF_CHANGES);
old-string <, new-string <, result-length <, truncation-value <,
number-of-changes>>>>); IF TRUNC THEN PUT "Note: NEW_TEXT was truncated";
DATALINES;
The Cat in the hat
There are two cat cats in this line
;
PROC PRINT DATA=CAT_AND_MOUSE NOOBS;
String Function
TITLE "Listing of CAT_AND_MOUSE";
repository RUN;

NEW_TEXT MATCH R_LENGTH TRUNC CHANGES


The Mouse in the hat 1 42 0 1
There are two Mouse Mouses in this line 1 44 0 2

20
Best place to work

Best place to bank

Arrays

Data Work.Arraydata;
DIM Input key 3. opened date9. purchcm01
purchcm02 purchcm03 purchcm04
The DIM function returns the number of literal elements in an array. purchcm05 purchcm06 5.;
Datalines;
It functions against multi-dimensional arrays as well as one-dimensional arrays. 1 01jan2009 100 150 350 700 800 850
2 15jan2009 0 0 100 1000 2000 2500
1-dimensional array example 3 20jan2009 50 100 200 400 900 1500
4 05feb2009 500 500 1000 2000 2500
DIM(array_name) 5000
;
Multi-dimensional array examples Run;

DIM(m_array) -> returns the number of elements in the first dimension of the array %MACRO COUNT(DSN);
DATA _NULL_;
DIM5(m_array) -> returns the number of elements in the 5th dimension of the array IF 0 THEN SET &DSN;

DIM(m_array, 5) -> returns the number of elements in the 5th dimension of the array ARRAY NUMS[*] _NUMERIC_;
ARRAY CHARS[*] _CHARACTER_;

N_NUMS = DIM(NUMS);
Data Arraydata; N_CHARS = DIM(CHARS);

Input key 3. opened date9. purchcm01 There are 8 numeric PUT / "There are " N_NUMS "numeric
Variables and0 Character Variables and" N_CHARS
purchcm02 purchcm03 purchcm04 Variables "Character Variables";
RUN;
purchcm05 purchcm06 5.; %MEND COUNT;
%COUNT(Work.Arraydata);

21
Best place to work

Arrays Best place to bank

 Array Implementation
Key opendate n_cob pur
DATA Arraydemo;
/* Defining arrays for variables used */
1 01jan2009 1 100
1 01jan2009 2 50
Array purch {6} purchcm01-purchcm06; 1 01jan2009 3 200
Set Arraydata; 1 01jan2009 4 350
1 01jan2009 5 100
DO I=1 TO 6; 1 01jan2009 6 50
n_cob=1; 2 15jan2009 1 0
IF purch {I} = . 2 15jan2009 2 0
THEN purch {I}=0; Key opendate pur1 pur2 pur3 pur4 pur5 pur6 2 15jan2009 3 100
2 15jan2009 4 900
IF (I>1) THEN DO;
2 15jan2009 5 1000
J = I-1; 1 01jan2009 100 150 350 700 800 850 2 15jan2009 6 500
purchase = SUM(purch {I}, -1 * purch {J}); 2 15jan2009 0 0 100 1000 2000 2500 3 20jan2009 1 50
End; 3 20jan2009 50 100 200 400 900 1500 3 20jan2009 2 50
Else purchase = purch {I}; 4 05feb2009 500 500 1000 2000 2500 5000 3 20jan2009 3 100
output; 3 20jan2009 4 200
END; 3 20jan2009 5 500
3 20jan2009 6 600
Run;
4 05feb2009 1 500
4 05feb2009 2 0
4 05feb2009 3 500
4 05feb2009 4 1000
4 05feb2009 5 500
4 05feb2009 6 2500

22
Best place to work

Date & Datetime functions Best place to bank

Making sense of SAS dates


Special case of a numeric variable
*Raw data as Input;
*Character data as Input;
December 30, 1959 <-> -2 data my_birthday;
December 31, 1959 <-> -1 infile cards; data _null_; set my_birthday;
January 1, 1960 <-> 0 input var1 mmddyy10.; sas_date =
cards; input(var1,mmddyy10.);
January 2, 1960 <-> 1
01/23/1963 run;
;
Range: 1588AD to 20000AD run;

Getting SAS equivalent of dates * Simple Date Functions;

Data _null_; data _null_;


Today = date(); my_birthday = '23jan63'd;
Testdate = ’23jan63’d; date1 = day(my_birthday);
firstdate = ’01jan1960’d; date2 = month(my_birthday);
Put ‘Log shows: ‘ today testdate date3 = year(my_birthday);
firstdate; date4 = qtr(my_birthday);
Run; date5 = weekday(my_birthday);
put date1 date2 date3 date4 date5;
Log shows: 17475 1118 0 run;
Log shows:
23 1 1963 1 4

23
Best place to work

Date & Datetime functions Best place to bank

Date Arithmetic
* Simple arithmetic functions with days;
data _null_;
date = date();
my_birthday = '23jan63'd;
datedif2 = intck('month',my_birthday,date); * intck(‘interval’, from, to );
datedif3 = sum(date,-my_birthday); * sum(to ,-from );
datedif1 = datdif(my_birthday,date,'act/act'); * datdif(from,to ,’act/act’) or ‘30/360’;
put ‘Log shows: ‘ datedif1 datedif2 datedif3;
run;
Log shows: 538 16357 16357

*INTCK (Computes interval between two date/datetime entities);

data _null_;
my_birthday = '23jan1963'd;
years = intck('year',my_birthday,date());
quarters = intck('qtr',my_birthday,date());
months = intck('month',my_birthday,date());
weeks = intck('week',my_birthday,date());
days = intck('day',my_birthday,date());
put ‘Log shows: ‘ years quarters months weeks days;
run;
Log shows: 44 176 529 2299 16092

24
Best place to work

Date & Datetime functions Best place to bank

Date Arithmetic Contd. * INTNX function – ‘time travel function’;

SAS Statements Results


date1=intnx('month','01jan95'd,5,'beginning')
; 12935
put date1 / date1 date7.; 01JUN95

date2=intnx('month','01jan95'd,5,'middle'); 12949
put date2 / date2 date7.; 15JUN95

date3=intnx('month','01jan95'd,5,'end'); 12964
put date3 / date3 date7.; 30JUN95

date4=intnx('month','01jan95'd,5,'sameday'); 12935
put date4 / date4 date7.; 01JUN95

date5=intnx('month','15mar2000'd,5,'same'); 14837
put date5 / date5 date9.; 15AUG2000
interval='month';
date='1sep2001'd;
align='m';
date4=intnx(interval,date,2,align); 15294
put date4 / date4 date7.; 15NOV01
x1='month ';
x2=trim(x1);
date='1sep2001'd + 90;
date5=intnx(x2,date,2,'m'); 15356
put date5 / date5 date7.; 16JAN02

25
Best place to work
Some useful date formats & Informats Best place to bank

26
Best place to work

Date & Datetime functions Best place to bank

Datetime functions all at one place


Date and Time Functions JULDATE7 returns a seven-digit Julian
DATDIF returns the number of days date from a SAS date value
between two dates MDY returns a SAS date value from
DATE/TODAY returns the current date as a SAS month, day, and year values
date value MINUTE returns the minute from a SAS
DATEJUL converts a Julian date to a time or datetime value
SAS date valueDATEPARTextracts the MONTH returns the month from a SAS date
date from a SAS datetime value value
DATETIME returns the current date and QTR returns the quarter of the year
time of day as a SAS datetime value from a SAS date value
DAY returns the day of the month from SECOND returns the second from a SAS
a SAS date value time or datetime value
DHMS returns a SAS datetime value from TIME returns the current time of Day
date, hour, minute, and seconds TIMEPART extracts a time value from
HMS returns a SAS time value from a SAS datetime value
hour, minute, and seconds WEEKDAY returns the day of the week from a
HOUR returns the hour from a SAS time SAS date value. WEEKDAY returns an integer
or datetime value that represents the day of the week, where
INTCK returns the integer number of 1=Sunday, 2=Monday,…, 7=Saturday
time intervals in a given time span YEAR returns the year from a SAS date
INTNX advances a date, time, or Value
datetime value by a given interval, YRDIF returns the difference in years between
and returns a date, time, or datetime two dates
valueJUL YYQ returns a SAS date value from the
DATE returns the Julian date from a year and quarter
SAS date value

INTCK & INTNX

27
Best place to work

SAS: Merge & Update Best place to bank

 The Neglected Update


 Merge combines two or more datasets updating values regardless of the new value.
 Update can combine only two datasets and if value is missing in update dataset its not changed
in target dataset

ID Var1 Var2 Var3


a 1 2 3 DATA MER; ID Var1 Var2 Var3 Var5 Var6
MERGE ID1(IN=A) ID2(IN=B);
b 4 5 6 a . 2 3 5 6
BY ID; b 4 5 6 . .
ID Var1 Var5 Var6 RUN; c 6 . . 3 1
a . 5 6
c 6 3 1

In a Nutshell! DATA UPD; ID Var1 Var2 Var3 Var5 Var6

Merge: Combining Datasets & UPDATE ID1 ID2; a 1 2 3 5 6


Forcing corrections BY ID; b 4 5 6 . .
Update: Selective corrections & RUN; c 6 . . 3 1
additions

28
Best place to work

SAS: Indexing Best place to bank

 What & Why of Indexing?!?!


A SAS Indexing is analogous to the search function allowing quick access to
datasets, speedy and efficient SAS programs.

How to create?
An Index is a physical file structure Types
1. PROC DATASETS
which serves as an adjunct to a 1. Simple Index
SAS data set principally containing 2. PROC SQL
INDEX variable and RECORD ID. 2. Composite Index
3. Data step

What else?!?!?! PROC DATASETS


LIBRARY=WORK;
Where can it be used? MSGLEVEL = I MODIFY ID1;
1. A WHERE statement in Data/Proc step INDEX CREATE ID/UNIQUE NOMISS;
IDXWHERE
QUIT;
2. A BY statement in Data/Proc step IDXNAME

PROC SQL;
SAS Institute Recommendation CREATE UNIQUE INDEX ID ON WORK.ID1
QUIT;
1. Index var have values which are frequently used in WHERE clause
2. Less than 25% have same value of Index variable
3. Uniform distribution of values of Index variable DATA TEST(INDEX=(ID /UNIQUE /NOMISS));
SET ID1;
RUN;

SAS Indexes

29
Best place to work
SAS: PROC IMPORT Best place to bank

PROC IMPORT How does it work?!?!


OUT = WORK.SOURCE
DATAFILE = “&PATH\TEST.EXT" • Scans the first 20 records.
DBMS = DLM REPLACE; • Collects the variable name from the first row.
DELIMITER=“,” ; • Scans remaining 19 rows to determine variable types.
GETNAMES = YES; • Assigns informat and a format to each variable.
MIXED = YES; • Creates an INPUT statement
DATAROW=3; • Submits the code to the DATA step compiler
GUESSINGROWS=1000; • Press F4 to recall the generated DATA step
RUN;

Specify the DLM for


Options available reading delimited files.
are EXCEL, When the column For Excel files option is
DLM & ACCESS. contains mix of redundant.
Use Sheet & Table NUMERIC & CHARACTER
with XL & Access DATA.
respectively. (especially with XL files)
Specifies the number of
records which SAS should
Behaves like FIRSTOBS. scan to determine type
Allows you chose the and length of variables.
starting row of the file.
Best place to work

Transporting files across platforms Best place to bank

PROC COPY method PROC CPORT/CIMPORT method

libname source 'SAS-data-library';


libname source 'SAS-data-library';
filename cportout 'transport-file';
libname xportout xport 'transport-file';
proc cport data=source.grades file=cportout;
proc copy in=source out=xportout memtype=data;
run;
select grades;
run; filename importin 'transport-file';
libname target 'SAS-data-library';
Data step method proc cimport infile=importin library=target memtype=data;
run;
libname source 'SAS-data-library';
libname xportout xport 'transport-file';
data xportout.grades;
set source.grades; Transporting files

run;

31
Best place to work

PROC DATASETS Best place to bank

Proc Datasets

32
Best place to work

PROC FORMAT Best place to bank

Basics

Proc format;
value BPInterp low-<120="Normal"
120-<140="Prehypertension" Interpretation N PctN
140-<160= "Stage 1 Hypertension" Normal 106 21.20
160-high="Stage 2 Hypertension" Prehypertension 189 37.80
;
Stage 1 Hypertension 169 33.80
run;
Stage 2 Hypertension 36 7.20
proc tabulate data=bp ; Total 500 100.00
class bp;
tables bp="" all="Total",(N
pctn)/box="Interpretation";
format bp BPInterp.;
run; data bp;
set bp;
length Interpret $21;
if bp < 120 then Interpret="Normal";
Advantage:
else if 120 <= bp < 140 then
HELPS
Interpret="Prehypertension";
Proc format REPLACE
else if 140 <= bp < 160 then
CODE LIKE:
Interpret="Stage 1 Hypertension";
else Interpret="Stage 2
Hypertension";
run;
Best place to work

Best place to bank

Picture formats

34
Best place to work

Best place to bank

Picture format

35
Best place to work

Best place to bank

Using predefined formats

data test;
input date : date9.;
datalines;
19SEP1999
23OCT1983
01SEP1980
01SEP2010
;
run;

proc format;
picture dispdate
low -< 10000 = [date9.]
10000 -< 15000 = [mmddyy8.]
15000 - high = "99,9999"
;

ods html file="v:\temp\predeffmt.html";


proc print data = test;
format date dispdate.;
run;

ods html close;

36
Best place to work

Best place to bank

Create store and re-use formats

Creates Format

Dumping to a dataset
proc format library=formats cntlout = fmt_dump;
select
pinstate;
run;

Uses Format

37
Best place to work

Best place to bank

Format Lookup

Format Lookup

38
Best place to work

PROC REPORT Best place to bank

proc report - simple

39
Best place to work

Best place to bank

USING THE COLUMNS STATEMENT

40
Best place to work

Best place to bank

USING THE DEFINE STATEMENT

ACROSS

41
Best place to work

Best place to bank

NESTING VARIABLES

42
Best place to work

Best place to bank

Proc report -
Compute

43
Best place to work

Best place to bank

Adding Images to
SAS reports

Proc report Styling

ExcelXp_attr_demo
ExcelXp_sample

44
Best place to work

PROC TABULATE Best place to bank

•Depicts formatted Pivot table like reporting


•Produces results upto 3-dimensions (X, Y, Page/table)

45
Best place to work

Best place to bank

Dimension 1st Level (Left) 2nd level (measure) Single col

46
Best place to work

Best place to bank

2D - 1

2D - 2

47
Best place to work

Best place to bank

48
Best place to work

Best place to bank

Multisheet Sample
ExcelXp

49
Best place to work

Best place to bank

ODS DESTINATIONS

proc report,
proc freq

Destination Result
SAS
Data Component Output Data Set

Output
Output Listing Window
Object
HTML
HTML File
Template
Components RTF
RTF File

style template,
table template
Best place to work

Best place to bank

PROC TEMPLATE Basics

Table and Style Templates Table Templates

Table and Style templates are the two main  Many table templates are shipped with SAS and they are used for

types of templates. displaying the output objects.

 Table templates provide instructions for  Table templates control data column order, column headers and

formatting a single output object. footers, and data formatting.

 Style templates provide presentation  A table template can be bound to an output object in a data step.

instructions for all output objects


produced. Style templates create a

consistent appearance of all SAS output. Style Templates


 Control how the results are displayed

Fonts, colours and borders.


 Applying a style to the ODS output

ods html file='sample1.html' style=default;

51
Best place to work

Best place to bank

Proc template contd…

Controlling the style ods markup file=“v:\Temp\sample.html"


tagset=tagsets.style_popup;
title 'Class List';
* To get the source of Styles.default;
footnote ‘Click on each element for its code';
proc template;
source styles.default; proc means data=sashelp.class min median max maxdec=1;
run; run;
ods markup close;

52
Best place to work

Best place to bank

Controlling the style – Colours and Fonts

“Safe” Fonts
“Safe” fonts1,2
Times New Roman, Times
Arial, Helvetica
Arial Black, Arial, Helvetica
Book Antigua, Times New Roman, Times
Courier New, Courier
Comic Sans MS, Arial, Helvetica
Verdana, Arial, Helvetica
Impact, Arial Black, Helvetica
Georgia, Times New Roman, Times
News Gothic MT, Arial, Helvetica
Tahoma, Arial, Helvetica
Trebuchet MS, Arial, Helvetica

Enlists many different predefined styles and other useful pointers on Styles
HTML_Styles
http://support.sas.com/rnd/base/topics/statgraph/v91StatGraphStyles.htm#Reference
http://support.sas.com/resources/papers/proceedings10/031-2010.pdf

53
Best place to work

Best place to bank

Controlling Tables via proc template define table Base.Contents.Variables;


notes "Contents Variables";
dynamic name_width name_width_max label_width label_width_max;
column Num Variable Type Len Pos Flags Format Informat Label
Transcode;
‘Odstemplates’ in the SAS command prompt header main;

define main;
text "Alphabetic List of Variables and Attributes";
space = 1;
spill_adj;
spill_margin;
end;

define Num;
header="/#/";
style=RowHeader;
id;
end;

define Variable;
header="Variable";
width_max=name_width_max;
width=name_width;
end;

define Type;
header="Type";
end;

define Len;
header="Len";
end;
... content snipped ...
col_space_max = 4;
col_space_min = 1;
newpage=off
balance;
end;

ods select variables;


proc contents data=sashelp.class;
run;

54
Best place to work

Best place to bank

Applying a table template to a dataset


proc template;
define table mytable;
column name (sex height) * (age weight); column name sex age height weight;
end;
run;

%macro do_table(dataset, template);


data _null_;
set &dataset;
file print ods=(template="&template");
put _ods_;
run;
%mend;

column name sex (age height weight); ods html file="v:\temp\test.html";


%do_table(sashelp.class, mytable);
ods html close;

55
Best place to work

Best place to bank

Creating and controlling headers & footers define table mytable;


column name sex age height weight;
define header first;
text 'First';
end;
define table mytable; define header second;
column name sex age height text 'Second';
end;
weight; define header third;
define header myheader; text 'Third';
end;
text "Class Information"; define header fourth;
end; text 'Fourth';
end;
end; end;

define table mytable;


column name sex age
height weight;
define header myheader;
text "Class Information";
start = name;
end = age;
end;
end;

define table mytable;


column name sex (age height
weight);
define age;
define header ageheightweight;
text 'Age*Height*Weight';
split = '*';
end;
header = ageheightweight;
end;
end;
56
Best place to work

Best place to bank

Advanced topics
define table mytable;
column name sex (age height weight);
define age;
• Adding new variables using compute define header ageheightweight;
text 'Age*Height*Weight';
define table mytable;
column name sex age height weight split = '*';
bmi; end;
define bmi; header = ageheightweight;
compute as (weight * 703) / (height * format = 3.;
height); end;
header = 'BMI'; define height;
format = 2.; format = 3.;
end; end;
end;
define weight;
format = 3.;
• Controlling style attributes end;
end;
define table mytable;
column name sex age height weight;
define height;
style = { font_weight=bold background=red foreground=white };
end; Reference:
define weight;
http://support.sas.com/rnd/base/ods/tem
style = { font_weight=bold background=red foreground=white }; plateFAQ/index.html
end; BLANK_DUPS
end; specifies that only the first occurrence of consecutive same
values should appear in a column.
JUST=
• Controlling column attributes: specifies the horizontal alignment of the cell content. The value
can be LEFT, RIGHT, or CENTER.
PRINT_HEADERS
specifies whether or not to print the column header.
VJUST=
specifies the vertical alignment of the cell content. The value
can be TOP, CENTER, or BOTTOM.

57
Best place to work

Introduction Best place to bank

MACROS
•A tool to customize SAS system
•Used to generate (often repeated or conditional) SAS code
•Modularizing code into reusable / portable program units
•Conditional compilation and execution of codes
OPTIMIZATION
•CPU Time
•Memory
•Data Storage
•I/O

AUTOMATION
•Library
•Date Manipulation
•Dataset Exists / Observations Count
•Scanning Log
•Mail

58
Best place to work

Best place to bank

CPU TIME I/O


• Drop & Keep • Read Only data what is needed
• Index • Eliminate unwanted data in the beginning
• Copy/Append • Copy/Append
• Consolidate Statements • Consolidate Statements
• Avoid Unnecessary Sorting • Compress datasets
• Use CLASS Statements • Store Data in SAS datasets not external files
• Pass-Through Facility • Views
• Views
• Format Usage

MEMORY
• Read only data that is needed
DATA STORAGE
• Complex SQL
• Usage of Drop & Keep
• Avoid SASFILE Statement
• Compress Options
SAS Options: Bufsize,Bufno,Fullstimer
• Length Statement
• Creation of Character variables/Formats

59
Best place to work

Best place to bank

VARIABLES - SCOPE SYMBOL TABLE


%Local :- Variables exist only during the execution of the macro Gcnt
in which the variables are created and have no meaning outside the Value
defining macro.
%Global:-Exist for the duration of the SAS session and can be Main MainM
referenced anywhere in the program--either inside or outside a
macro. Cnt
Mcall
%Let gCnt = 4;
Mcall2 Int
%Macro Mcall2;
%Global Value; %Let Int=0;
%Let Cnt = %Eval(&Cnt+&gcnt);
%Let Value = %Eval(&gcnt-&Cnt);
%Mend;

%Macro Mcall;
%Local cnt; VARIABLE : EXIST/DELETE/SCOPE
%Let Cnt=1;
%MCall2; %LET VAR = 10;
%Put &Cnt &Value; %If %SYMEXIST(VAR) %Then %Do;
%Mend Mcall; …..
%Macro Main; %End
%Let MainM = 10;
%Mcall; %SYMDEL VAR;
%Put &Value &Cnt; %If %SYMLOCAL(VAR) %Then %Do;
%Mend Main; …….
%Main; %End

60
Best place to work

Best place to bank

FUNCTIONS AUTOCALL MACROS


%LENGTH : %TRIM and %QTRIM
Returns the length of a string Trim trailing blanks

%SCAN,%QSCAN : %LEFT and %QLEFT


Search for a word that is specified by its position in a string Left-align an argument by removing leading blanks

%INDEX : %LOWCASE and %QLOWCASE


Returns the position of the first character of a string Change uppercase characters to lowercase

%SUBSTR,%QSUBSTR: %CMPRES and %QCMPRES


Produce a substring of a character string Compress multiple blanks and remove leading and trailing blanks

%SYSFUNC,%QSYSFUNC: OPTIONS
Execute SAS functions or user-written functions MACRO
%LET X=%SYSFUNC(TRIM(%SYSFUNC(LEFT(&NUM)))); Controls whether the SAS macro language is available
%SYSGET MERROR
Returns the value of the specified operating environment variable Controls whether the macro processor issues a warning
%Let USERID=%sysget(USER); message when a macro reference cannot be resolved
%put User is &person;
MAUTOSOURCE
RESOLVE :
Controls whether the autocall feature is available
Resolves the value of a text expression during DATA step execution
%let event=Holiday; MCOMPILENOTE
%macro date; New Year %mend date;
Issues a NOTE to the log upon the completion of the
data test; length var1-var3 $ 15;
when='%date'; compilation of a macro
var1=resolve('&event'); /* macro variable reference */
MLOGICNEST
var2=resolve('%date'); /* macro invocation */
var3=resolve(when); /* DATA step variable with macro invocation */ Allows the macro nesting information to be displayed in the
put var1= var2= var3=; run; SAS log
MSTORED
Controls whether stored compiled macros are available

61
Best place to work

Best place to bank

EXPRESSIONS LOOPING
%EVAL:- converting its argument from a character value to a %Do %While(Expression);…%End;
numeric or logical expression. Then, it performs the evaluation, Executes a section of a macro repetitively based on the value of an
converts the result back to a character value and returns that value. index variable
Eg. %Do %Until(Expression);… %End;
%Let Value = %Eval(&A+&B); Executes a section of a macro repetitively until a condition is true
%Let ArVal=%Eval(&A>&B); %Do MacroVariable=Start %To Stop <%BY>;… %End;
Executes a section of a macro repetitively based on the value of an
index variable
%SYSEVAL:- Evaluates arithmetic and logical expressions using %Macro RenameVar(Type=);
floating-point arithmetic %Let Cnt=1;
Eg. %Do %Until( &Var1 eq %Str( ));
%Let Var1=%Scan(&AnalyVar,&Cnt,%str( ));
%Let Value = %Eval(10.5+25.6); %if &Var1 Eq %Then %Goto Ext;
%Let ArVal=%Eval(10.5+25.6,CEIL); &Var1=&Var1._&Type
%Let Cnt = %Eval(&Cnt+1);
%IF Expression %THEN …. <%ELSE> … %Ext:
%Macro RptGen(Input=); %End;
%If &Input=Weekly %Then %Do; %Mend RenameVar;
Proc Summary Data = WeekData; Class Prod; Var Balance; Run;
%End; %Let AnalyVar=Test1 Test2 Test3 Test4 Test5;
%Else %If &Input=Monthly %Then %Do; Data Test;
Data MonthEnd; Merge xx1 (Keep=Pm &Analyvar Rename=(%RenameVar(Type=H1)))
Merge MonthEnd(In=Table1) Regions; by CustId; If Table1; xx2 (Keep= Pm&analyvar Rename=(%RenameVar(Type=H2)));
If Region='CA' Then Delete; Run; by Pm;
Proc Summary Data= MonthEnd; Run;
Class Prod; Var Balance; %Macro Clean;
Run; %Do I = 1 %to 25;
%End; %Symdel Prod&I;
%Mend RptGen; %End;
%RptGen(Input=Weekly); %Mend Clean;

62
Best place to work

Best place to bank

QUOTING
%STR and %NRSTR : SUPERQ:
 Mask the item during macro compilation Retrieves the value of a macro variable from the macro symbol table
and quotes it immediately, preventing the macro processor from
 If an unmatched single or double quotation mark or a left or
making any attempt to resolve anything that might occur in the
right parenthesis is used with %STR or %NRSTR, these
resolved value.
characters must be preceded by a percent sign (%).   
Data _NULL_;
%let myvar=%str(a%'); X = 'Report Generation For Region1 &Region2';
%Let CurrDate=’31Dec2009’d; Call symput('RTitle',x);
%Let Titletext=%NrStr(Report for Region1 &Region2); Run;
%Let SQ=%Superq(Rtitle);
%Put &Sq;
%BQUOTE and %NRBQUOTE :
 Mask values during execution of a macro or a macro language UNQUOTE
statement in open code.
During macro execution, unmasks all special characters and
 Mask all the characters, with the addition of unmarked percent mnemonic operators for a value
signs; unmatched, unmarked single and double quotation
marks; and unmatched, unmarked opening and closing %let val = aaa;
parentheses. %let testval = %str(%'&val%');
%Macro test;
data _null_;
%Do I = 1 %to 10; val = %unquote(&testval);
%Let d = %sysfunc(intnx(Month,17834,&i,E),date9.); put 'VAL =' val;
%Let D1 = %bquote('&D'd); %Put &d1;
%End;
run;
%Mend Test;
%test; 
SYMBOL TABLE CONTENTS
%if %bquote(&Path) eq %then %do; _ALL_: Describes all currently defined macro variables
%Put ERROR: Path is Missing;
_AUTOMATIC_: Describes all automatic macro variables.
%end;
_GLOBAL_: Describes all user-defined global macro variables
_LOCAL_:Describes user-defined local macro variables
_USER_ : Describes all user-defined macro variables, regardless of scope.
63
Best place to work

Best place to bank

SET vs APPEND BUFSIZE & BUFNO ENCRYPT

Data Test(Bufsize=512K); Data PII(Encrypt=Yes Read=Pswd


Data all;
Set Demart; Write=Test);
Set Test.Demart200906 Test.Demart200905
Run; Set Test;
Test.Demart200904;
Run;
Run;
Data Test1;
Set Test(BufNo=2) Proc Means data = PII(Read=Pswd);
real time 6:44.00
Run; Var Balance;
user cpu time 2:22.79
Run;
system cpu time 1:11.75 Increasing either Bufsize or Bufno
Memory 1191k increase the amount of data that can be To Use this dataset you need to
transferred in read operation provide Read/Write password

INDEX &COMPRESS IDXWHERE & IDXNAME


Proc Datasets Lib=Test;
Append Base=Work.all1 data=Test.Demart200906; Data Test(Compress=Yes Index=(Id)); Data Test;
Append Base=Work.all1 Data=Test.Demart200905; Set Test; Set Mart(Idxwhere=Yes);
Append Base=Work.all1 Data=Test.Demart200904; If prod_cde in (‘XXX’,’QQQQ’) Then Where Prod_cde in
Run; Delete; (‘XXXX’,’QQQQ’)
Quit; Run; Run;

real time 4:18.00 Forces SAS to use an Index


Proc Freq data= Test;
user cpu time 2:05.00 By Id; Data Test;
system cpu time 1:09.27 Table Cust_Seg / List; Set Mart(Idxname=Prod_cde);
Memory 452k Run; Where Prod_cde in (‘VVVV’);
Run;
Dataset is not sorted, but Proc freq
utilizes the index for by group
Forces SAS to use Specific index
processing 64
Best place to work

Best place to bank

PASS THROUGH FACILITY


Proc Sql; Data Mdbal;
Connect To Db2 As HsbcHdw(User=&Dpwuscod. Set udblib.Hdw_Dda_Eom_Snap
Pass=&Dpwpwcod. Database=&Dpwdbnam.); (Keep=Arr_id_acct Bal_Ldgr_Amt Snap_dt Prod_cde);
Create table testing1 as select * from Connection to if snap_dt = '28Feb2010'd;
HsbcHdw Run;
(
real time 17:43.00 user cpu time 1:30.36
select Prod_cde,sum(bal_ldgr_amt) as tot_bal
system cpu time 11.08 seconds Memory 804k
from Hdwp001.hdw_dda_eom_snap
where snap_dt = '02/28/2010' Proc SQL;
Group by Prod_cde Create table Testing as select Prod_cde,Sum(Bal_Ldgr_Amt) as Tot_bal
); from Mdbal
Quit; Group by Prod_cde;
real time 0.00 seconds user cpu time 0.01 seconds Quit;
system cpu time 0.00 seconds Memory 107k
real time 2.00 seconds user cpu time 2.13 seconds
Proc Sql;
system cpu time 0.44 seconds Memory 921k
create table test as select Prod_cde,Sum(bal_ldgr_amt) as
totbal
Proc Tabulate data = Mdbal Out=testing ;
from udblib.Hdw_dda_eom_snap
class Prod_Cde;
where snap_dt = '28feb2010'd
var bal_ldgr_amt;
Group by prod_cde;
table Prod_Cde,bal_ldgr_amt;
Quit;
Run;
real time 5.00 seconds user cpu time 0.00 seconds
system cpu time 0.01 seconds Memory 706k real time 1.00 seconds user cpu time 1.13 seconds
system cpu time 0.25 seconds Memory 1421k

65
Best place to work

Best place to bank

UPLOAD DATA TO DB2 AND EXTRACT


Libname UserData db2 user=&dpwuscod. using=&dpwpwcod.
Proc Sql; db=&dpwdbnam. schema=TEMP;
Connect To Db2 As Hsbcdb (User=&dpwuscod.
Password=&dpwpwcod. Database=&dpwdbnam.); data Userdata.Test;
Create table testing as select * from Connection to Hsbcdb set Test(keep=Ip_Id_Cust);
( Run;
Select Ip_Id_Prim_Cust,bal_ldgr_amt as balance real time 0.00 seconds user cpu time 0.01 seconds
From hdwp001.hdw_dda_eom_snap system cpu time 0.00 seconds Memory 750k
Where Snap_dt >='02/28/2010'
); Proc Sql;
Quit; Connect To Db2 As Hsbcdb (User=&dpwuscod.
real time 12.00 seconds user cpu time 1.55 seconds Password=&dpwpwcod. Database=&dpwdbnam.);
system cpu time 0.22 seconds Memory 706k Create table testing as select * from Connection to Hsbcdb
(
Proc sql; Select Ip_Id_Prim_Cust,Sum(bal_ldgr_amt) as balance
create table testing1 as select ip_Id_prim_Cust,sum(balance) From hdwp001.hdw_dda_eom_snap,Temp.test
as balance Where Snap_dt >='02/28/2010' And ip_id_prim_cust=Ip_Id_cust
From testing, test group by Ip_Id_Prim_Cust
where Ip_id_prim_cust=ip_id_cust );
group by ip_id_prim_cust; Quit;
Quit; real time 8.00 seconds user cpu time 0.00 seconds
real time 1.00 seconds user cpu time 0.82 seconds system cpu time 0.00 seconds Memory 706k
system cpu time 0.04 seconds Memory 1654k

66
Best place to work

Best place to bank

PATH EXIST LIBRARY ASSIGN DATASET EXIST


%Macro PathExist(Path=); %Macro LibAssign(Path=); %Macro DsCheck(DataSet=)
%Let FlChk=%sysfunc(Fileexist(&Path)); Libname Temp “&Path”;
%if not %Sysfunc(exist(Dscheck.&Dataset))
%if &Flchk=0 %then %do; %if &SysLibRc=0 %then %do;
%then %do;
%Put ERROR: &Path does not exist; %Put Assigned Library;
%end; %end; %put ERROR: &Dataset does not exist.;
%MEnd; %Mend; %MEnd;
OBSERVATION COUNT SCANNING VARIABLES
%Macro ObsCnt(Ds=); %Macro __Chkvar(Variable=);
%Let Found=0;
%Let Dsid=%Sysfunc(Open(Dscheck.&Dataset,is)); %do I = 1 %to %sysfunc(Attrn(&dsid,Nvars));
%if &Dsid=0 %then %do; %Let Varname= %qcmpres(%upcase(%sysfunc(Varname(&Dsid,&i))));
%if &Varname=%upcase(&Variable) %then %do;
%Put %sysfunc(sysmsg()); %Let Found=1;
%Put Note: Variable &Variable Found in Dataset;
%End; %goto Out;
%Else %Do; %end;
%end;
%Let Nobs==%sysfunc(Attrn(&Dsid,NOBS)); %Out:
%if Not &Found %then %Put ERROR: Variable &Variable Not Found;
%if &Nobs=0 %then %do; %mend __ChkVar;
%Put ERROR: Zero Observations in &Dataset; %Macro VarScan(varnames=);
%Let FirstVar=%Scan(&Varnames,1,%str( ));
%End; %Let Cnt=1;
%Do %Until (&Firstvar Eq);
%MEnd; if &FirstVar Ne %then %Do; %__ChkVar(&FirstVar); %End;
%let Rc=%sysfunc(close(&dsid)); %Let Cnt=%Eval(&cnt+1); %Let FirstVar=%Scan(&Varnames,&Cnt,%Str( ));
%End;
%Mend;

67
Best place to work

Best place to bank

SYSERR SYSINFO
0 Execution completed successfully and without warning messages. Proc compare base=Base Compare=New;
4 Execution completed successfully but with warning messages.
Run;
>4 An error occurred. The value returned is procedure dependent.
%Let Compare = %Sysfunc(putn(&SysInfo,binary16.))
%Macro CheckError;
Bit Condition Description
%If &SysErr >=4 %Then EndSas;
%Mend CheckError; 1 DSLABEL Data set labels differ

2 DSTYPE Data set types differ

3 INFORMAT Variable has different informat

DATE MANIPULATIONS 4 FORMAT Variable has different format

5 LENGTH Variable has different length

6 LABEL Variable has different label

%Macro DateAdvanced(Unit=,Date=,Advancedby=); 7 BASEOBS Base data set has observation not in comparison

%Let Date=%Sysfunc(Inputn(Date,Date9.));
8 COMPOBS Comparison data set has observation not in base
%If &Unit = DAYS %Then %Do;
%Let Date=%Eval(&Date+&Advancedby); 9 BASEBY Base data set has BY group not in comparison

%End; 10 COMPBY Comparison data set has BY group not in base

%Else %Do;
11 BASEVAR Base data set has variable not in comparison
%Let Date=%Sysfunc(Intnx(&Unit,&Date,Advancedby,E));
12 COMPVAR Comparison data set has variable not in base
%End;
%Mend DateAdvance; 13 VALUE A value comparison was unequal

%DateAdvanced(Unit=DAYS,Date=30Mar2010,10); 14 TYPE Conflicting variable types

15 BYVAR BY variables do not match

16 ERROR Fatal error: comparison not done

68
Best place to work

Best place to bank

SCANNING LOG ASYNCHRONOUS TASKS


Proc Printto Log='/home/b50978pf/Rslt.log'; Systask Command “SAS Test.sas –log test.log –print test.lst" taskname=sme Nowait
Run; Status = Programstatus ;
Filename ErrScan '/home/b50978pf/Rslt.log';
%Include ‘/home/xxxxxx/Secondprogram.sas’;
Data Error; Waitfor Sme Timeout=30000;
Infile ErrScan ; Data All;
Input; Merge test second;
If index(_infile_,'ERROR:')>0 Then Do; By key;
Call Symput('ERR_CDE','1'); Run;
Stop;
End; SYNCHRONOUS TASKS
Run;
Filename ErrScan Clear; Systask Command “SAS Test.sas –log test.log –print test.lst" taskname=pgm Wait;
Data All;
Proc Printto; Set Test;
Run; Run;

MAIL FILE PERMISSION


filename mymail email ‘xxxxxxx@usvh2euap2a.us.hsbc'; Filename Myfile Pipe 'Ls -Ltr /Home/B50978pf/Test.Log';
data _null_; Data Test;
file mymail to=(‘xxxxxxxx@hsbc.co.in') From="Test Infile Myfile Lrecl=256;;
Process<xxxxx@usvh2euap2a.us.hsbc>" Input;
Subject="Testing the Process" Attach=('/home/xxxxx/test.log'); Per = Upcase(Substr(_Infile_,1,10));
run; If Substr(Per,5,1)='R' Then
filename mymail Clear; Call Symput('Permission','1');
Else Call Symput('Permission','0');
Run;
Filename Myfile Clear;
69
Best place to work

Best place to bank

APPENDIX – CODE MODULES

Sample code modules.zip

70

You might also like