m4 allows the user to define macros which can then be used in developing applications. After a macro is defined, using a built-in macro called define, it is replaced by its definition in any file which uses the macro and which is preprocessed by m4. This process of replacement by a definition is called evaluation. For example, if the file query1.m contains the text
define(_eqn, `(1 -abs(sign($1 - $2)))') /* equal to */
select oneonly = sum(_eqn(au_ord,1) - _eqn(au_ord,2)),
two2four = sum(_eqn(au_ord,2) - _eqn(au_ord,5)),
many = sum(_eqn(au_ord,5))
from authortitle
go
and is preprocessed as above with m4 the SQL code in our first example will be produced. m4 uses $1 and
$2 as place markers in the macro definition for arguments used later on when the predefined macro
is actually encountered and processed. Thus $1 and $2 hold the place of later arguments such as au_ord and 1.
The quotes ` and ' are used to delay expansion of additional macros
used inside the definition of a macro until it is actually used. When the macro
_eqn(au_ord,1) is expanded, au_ord replaces $1 and 1 replaces $2 at which point the
entire _gen macro is replaced by its definition, sign((1
- abs(sign(au_ord - 1)))), with the appropriate
substitutions.
Something should be said about notation. We use the underscore character to begin all macros so as to ensure they will be easily recognized in any Transact-SQL code. The macro name _eqn stands for equal (numeric). This allows for other macro definitions such as _ged for greater than or equal (date).
To avoid cluttering up a file containing a stored procedure definition with too many macro definitions these definitions can be placed in a second file and included in the stored procedure definition file. The built-in macro include does this.
include(macro_defs.m)
Unless otherwise indicated, all macro definitions are assumed to be found in the file macro_defs.m.