Production Ready Macros for SAS Application Developers
mp_searchdata.sas
Go to the documentation of this file.
1 /**
2  @file
3  @brief Searches all data in a library
4  @details
5  Scans an entire library and creates a copy of any table
6  containing a specific string or numeric value. Only
7  matching records are written out.
8  If both a string and numval are provided, the string
9  will take precedence.
10 
11  Usage:
12 
13  %mp_searchdata(lib=sashelp, string=Jan)
14  %mp_searchdata(lib=sashelp, numval=1)
15 
16 
17  Outputs zero or more tables to an MPSEARCH library with specific records.
18 
19  <h4> Dependencies </h4>
20  @li mf_getvarlist.sas
21  @li mf_getvartype.sas
22  @li mf_mkdir.sas
23  @li mf_nobs.sas
24 
25  @version 9.2
26  @author Allan Bowe
27 **/
28 
29 %macro mp_searchdata(lib=sashelp
30  ,ds= /* this macro will be upgraded to work for single datasets also */
31  ,string= /* the query will use a contains (?) operator */
32  ,numval= /* numeric must match exactly */
33  ,outloc=%sysfunc(pathname(work))/mpsearch
34 )/*/STORE SOURCE*/;
35 
36 %local table_list table table_num table colnum col start_tm vars type coltype;
37 %put process began at %sysfunc(datetime(),datetime19.);
38 
39 
40 %if &string = %then %let type=N;
41 %else %let type=C;
42 
43 %mf_mkdir(&outloc)
44 libname mpsearch "&outloc";
45 
46 /* get the list of tables in the library */
47 proc sql noprint;
48 select distinct memname into: table_list separated by ' '
49  from dictionary.tables where upcase(libname)="%upcase(&lib)";
50 /* check that we have something to check */
51 proc sql;
52 %if %length(&table_list)=0 %then %put library &lib contains no tables!;
53 /* loop through each table */
54 %else %do table_num=1 %to %sysfunc(countw(&table_list,%str( )));
55  %let table=%scan(&table_list,&table_num,%str( ));
56  %let vars=%mf_getvarlist(&lib..&table);
57  %if %length(&vars)=0 %then %do;
58  %put NO COLUMNS IN &lib..&table! This will be skipped.;
59  %end;
60  %else %do;
61  /* build sql statement */
62  create table mpsearch.&table as select * from &lib..&table
63  where 0
64  /* loop through columns */
65  %do colnum=1 %to %sysfunc(countw(&vars,%str( )));
66  %let col=%scan(&vars,&colnum,%str( ));
67  %put &col;
68  %let coltype=%mf_getvartype(&lib..&table,&col);
69  %if &type=C and &coltype=C %then %do;
70  /* if a char column, see if it contains the string */
71  or (&col ? "&string")
72  %end;
73  %else %if &type=N and &coltype=N %then %do;
74  /* if numeric match exactly */
75  or (&col = &numval)
76  %end;
77  %end;
78  ;
79  %if %mf_nobs(mpsearch.&table)=0 %then %do;
80  drop table mpsearch.&table;
81  %end;
82  %end;
83 %end;
84 
85 %put process finished at %sysfunc(datetime(),datetime19.);
86 
87 %mend;