Pervasive Data Integrator Scripting in Data Integrator
Below you will find brief information for Data Integrator. This manual explains how to write and use EZscript expressions within Pervasive Data Integrator for data mapping, manipulation, and filtering. Learn about operators, functions, statements, and regular expressions to manage data effectively. The guide covers both basic and advanced expression writing techniques, including date handling and data type validation.
Advertisement
Advertisement
Scripting in Data Integrator
Scripting in Data Integrator
Data Integrator offers a scripting language that allows you to write your own scripts and
expressions to include with your processes and transformations. A script is a repository
artifact containing a snippet of code that can be directly evaluated by the scripting engine
to produce a result. Expressions very similar to scripts, but are normally stored as part of
one of the larger artifacts.
The EZscript scripting language includes functions, operators, statements, variables,
object variables, and error objects. EZscript is similar to Visual Basic (VB), but there are
some notable differences. This list outlines the main differences:
• EZscript variables are all variant. For more details about variants, see Variant Data
Type.
• EZscript supports both functions and subroutines (a user-defined function may or may
not pass back a value). The scripting language does not distinguish between them in
the definition.
• EZscript is supported in both Windows and Unix platforms.
• EZscript does not include all VB script functions. However, EZscript includes custom
functions that are nonexistent in VB, such as the file management functions FileRead
and FileRename.
This section includes the following topics:
•
•
•
•
•
•
•
•
•
•
Writing Expressions
Basic Elements of an Expression
Scripting Keywords
Precedence in Evaluating Expressions
Commenting Out Code
Quotation Marks in Expressions
Specifying Field Names in Expressions
Continuing Lines in Expressions
Regular Expressions
Literal Values in Expressions
Writing Expressions
Learning how to write expressions is important if you want to:
• Map and manipulate the data from the source to the target file
• Select records meeting a certain criteria for the target file (filtering)
1
If you are just beginning to write and modify expressions, you may want to review Basic
Elements of an Expression.
These sections help you write your expressions to get the desired data into your target file.
You are a basic user and want to
See
Define parts of expressions and types of operators.
Basic Elements of an Expression
Specify source field names in expressions.
Specifying Field Names in Expressions
Nest expressions within expressions and set precedence in
expressions.
Writing Expressions
Specify literal values (constants) in expressions.
Literal Values in Expressions
Ensure that dates are read properly from your source file and
written as you want in your target file.
Managing Dates
You are an advanced user and want to
See
Use the correct statement for the job.
Statements
Use arrays correctly in your expressions.
Dimensions of Variables
Interpret data typing errors in my expressions.
Validating Data Types in Expressions
Learn what functions use regular expressions, and what
characters to use in them.
Regular Expressions
Call an ActiveX object without leaving the application to look up
object syntax.
EZscript Expressions
Basic Elements of an Expression
There are five basic elements of an expression:
•
•
•
•
•
Operands
Operators
Parentheses
Functions
Statements
Operands
Operands are values or text that the formula operates on. These may be actual values,
such as "4", or field names (including text or numeric fields).
2
Scripting in Data Integrator
Operators
Operators are mathematical symbols, text characters, or logical statements that tell the
application what to do with the operands in a formula. The scripting operators are very
similar to those in Microsoft Excel.
There are several types of operators:
•
•
•
•
•
•
Recognition Rule Operators
Arithmetic Operators
Assignment Operator
Logical Operators
Comparison Operators
Concatenation Operator
Parentheses
You can use parentheses in complex formulas to determine the order in which you want
formulas calculated. Operations within parentheses are executed first.
See Precedence in Evaluating Expressions.
Example of Nested Parentheses
(Field + Field * (Field - Field)/ Field)
Functions
Functions are snippets of code that perform specific tasks. Use them in expressions to
manipulate data or filter records. The functions available are similar to the functions in
Visual Basic.
Statements
Statements are standalone elements used to form programs. Statements often call
functions and include internal components, such as expressions.
Scripting Keywords
The scripting language encompasses functions, statements, and keywords that are used in
source and target filters, target field expressions, and scripts. It also employs many unique
functions, which were designed to help you get the most out of your data. You may
recognize VBScript, some Visual Basic functions, and some SQL statements.
3
Category
Keywords
Array Handling
IsArray function
Declaration (Dim, Static, etc.)
LBound
UBound
ReDim
DJRowSet object type
Assignment
Let, Set statements
Comments
(apostrophe): Comment out one line of code
CStyle: Comment out a block of code
Constants/Literals
Empty, Nothing, Null
True, False
User-defined literals
Flow Control
For. . . Next, For Each...Next statements
While. . . Wend statement
If. . . Then. . . Else statement
Select. . . Case statement
Function statement
Conversion
Abs, Asc, Chr functions
CBool, CByte functions
CDate, CDbl, CInt functions
CLng, CSng functions
Fix, Int, Sgn functions
Bin, Hex, Oct functions
Internal Objects
4
DJExport, DJImport objects
Scripting in Data Integrator
Category
Keywords
DJField, DJRecord objects
Err, Sys objects
Data type
Integer, Long, Single, Double
String (must be declared ByVal)
Date/Time
CDate, Date, Time functions
Day, Month, Weekday, Year functions
Hour, Minute, Second functions
Now, DateAdd, DateConvert functions
DateDiff, DatePart functions
DateSerial, DateValMask, DateValue functions
FileDateTime function
IsDate, TimeSerial, TimeValue functions
Error Handling
On Error GoTo statement
On Error Resume Next statement
Err Object statement
Reject function
File/Directory Management
FileAppend, FileCopy functions
FileDateTime, FileDelete functions
FileExists, FileLen, FileList functions
FileRead, FileReadLine, FileRename functions
FileWrite, IsFile functions
ChangeDirectory, GetDirectory functions
IsDirectory, MakeDirectory functions
RemoveDirectory function
Input/Output
InputBox function
5
Category
Keywords
LogMessage function
Math
Abs, Exp, Fix, Int functions
Log10, Rnd, Round functions
Sgn, Val, ValMask functions
Modules
Dim statement
Sub function
ByVal (ByRef)
Objects
CreateObject function
GetObject, IsObject functions
Operators
+, -, *, /, ^, Mod operators
Integer Division (\) operators
Negation (-) operator
String concatenation (&) operator
=, <>, <, >, <=, >=, == operators
Not, And, Or operators
Options
Option Explicit, Option Implicit statements
Regular Expressions
GSub, Sub functions
~ operator, !~ operator
Like operator
Strings
Asc, Chr, InStr functions
Len, LCase, UCase functions
Left, Mid, Right functions
Space(number) function
StrComp function
String(number, character) function
6
Scripting in Data Integrator
Category
Keywords
Trim, LTrim, RTrim functions
Variables
Dim, Set, Static statements
Private, Dim, ReDim statements
User-defined functions
Option Explicit statement
Variants
IsArray, IsDate functions
IsNull function
IsNumeric, IsObject functions
See Also
Regular Expressions
Precedence in Evaluating Expressions
Operators in expressions are evaluated in the following order:
1
exponentiation
2
mutiplication and divison
3
addition and subtraction
The only exception is that operations within parentheses, such as (a+x), are executed first.
To use the result of one expression as a parameter or argument in another expression,
"nest" expressions within expressions. Remember that expressions inside parentheses are
executed first. There is generally no limit (except available memory) to the depth of
nesting.
See Also
Dimensions of Variables
Option Base Statement
Commenting Out Code
If you want to comment out a block of code, do one of the following:
• Type a single quote (') at the beginning of each line.
7
• Use C-Style commenting by typing a forward slash and asterisk (/*) at the beginning
and at the end of your comment, as follows:
/* If Len(Trim(FieldAt("/SOURCE/R1/Field1")))=0 Then
"No data exists"
Else
FieldAt("/SOURCE/R1/Field1")
End if */
Quotation Marks in Expressions
Any quotation marks that appear in code must be straight quotation marks ("). Curly
quotation marks (“ ”), which are often the result of pasting text from an external
program, are not valid characters for EZscript and will cause script validation to fail.
Specifying Field Names in Expressions
When working with any number of records, you can specify the field name in an
expression by using the FieldAt Function.
Note To specify a record, use the RecordAt Function (RecordAt("/SOURCE/R1")).
Use the following format to reference fields:
FieldAt("/SOURCE/R1/Field1")
Example
If you have a record called “Parent” and a field called “Initials”, then the reference looks
like this:
FieldAt("/SOURCE/Parent/Initials")
Field names are case-sensitive and must be written exactly as they appear in the record
layout grid. When using Script Editor to write expressions, you can select field names from
the list in its interface to quickly enter the names in the correct case and syntax.
Target field names do not appear in the list within Script Editor, but you can still reference
target fields using the same format as source fields:
FieldAt("/TARGET/R1/Field1")
If you enter a field name without using FieldAt, the name is interpreted as a variable. If no
such variable has been defined and initialized, it is treated as a variable with an empty
string.
8
Scripting in Data Integrator
Continuing Lines in Expressions
Sometimes expressions are so long that you cannot view them without scrolling. To view
your expressions broken into viewable segments, use the following syntax:
<space><underscore><carriage return line feed>
Also, do the following in your expressions:
• use an ampersand “&” to concatenate strings together
• include spaces in strings so that words are properly separated (spaces are added to the
end of each line in the example below)
Example
var.SQLStatement = "SELECT * " _
& "FROM TABLENAME " _
& "WHERE COLUMNNAME = VALUE"
The resultant query looks like this:
var.SQLStatement = "SELECT * " & "FROM TABLENAME " & "WHERE
COLUMNNAME = VALUE"
Regular Expressions
A regular expression is a string of characters that defines a set of rules for matching
character strings. Regular expressions can match a whole string or a portion of a string. An
exception is the Like operator (see Escaping Hex Values).
Scripting allows you to use regular expressions with certain functions and operators.
Regular expressions can specify more complex and flexible conditions for matching
character strings than simply a test of "Is it the same string?"
This section contains the following information regarding using regular expressions in
scripts:
• Special Characters
• Literal Values of Special Characters
• Functions and Operators
Special Characters
When used in a function or with an operator that enables regular expressions the
following characters have special meanings: "|", "(", ")", "*", "+", "?", "[", "]", "-", ".", "\",
"^" and "$".
9
When writing regular expressions, remember these special characters and their purposes.
Character
Meaning
|
Divides an expression into branches and then the overall expression matches any field which
matches any of the branches.
For example, "Sam|Carol" matches all fields which contain either or both of the strings "Sam"
or "Carol". For information on how this character behaves differently when used with Like,
see Like Operator.
(xxxx)
Characters in parenthesis are treated by the subsequent special character the same as a
single character is treated.
For example, "abc*" matches "abc", abcc", and abccc", whereas (abc)* matches "abc",
"abcabc", and "abcabcabc".
*
Any character or group followed by "*" matches zero or more occurrences of the previous
character or group in a field.
Thus "Sam*y" matches "Say" (zero occurrences of "m"), "Samy" (one occurrence of "m"),
"Sammy" (two occurrences of "m"), and "Sammmy" (three occurrences of "m"). In the same
way, "Rin(tin)*" matches "Rin", "Rintin", "Rintintin", and "Rintintintin".
+
Any character or group followed by "+" matches one or more of that character or group in a
field.
"Sam+y" does not match "Say" but matches "Samy", "Sammy", "Sammmy", etc. "Rin(tin)+"
does not match "Rin" but matches "Rintin", "Rintintin", "Rintintintin", etc.
?
Any character or group followed by "?" matches either zero or one of that character or group
in a field.
So, "Sam?y" matches either "Say" or "Samy" but not "Sammy". "Rin(tin)?" matches "Rin" or
"Rintin".
{n,m}
Two numbers separated by a comma and enclosed in curly brackets, "{ }", can be used to
specify a set or class of repetitions of the previous character or group. The first number
indicates the minimum number of repetitions, and the second number indicates the
maximum. The second number is optional. If it is omitted, there is no upper limit for
repetitions.
For example, "Sam{0,2}y" matches "Samy", "Sammy" but not "Sammmy". "Rin(tin){2}" does
not match "Rintin" but matches "Rintintin" and "Rintintintin".
[xxxx]
A sequence of characters enclosed in square brackets, "[ ]", constitutes a set. It normally
matches any character within the sequence. Thus "Pa[tml]" matches "Pat", "Pam", or "Pal".
If the sequence begins with a '^', the set or class matches any character not in the sequence.
Thus "Pa[^tml]" matches any three-character sequence starting with "Pa" and ending with
any character except 't', 'm', 'l'.
10
Scripting in Data Integrator
Character
Meaning
[x-y]
Two characters separated by '-' represents a set or class, or a full list of ASCII characters
between them. Thus "Pa[0-9]" matches any three-character string starting with "Pa" and
ending with a digit. "Pa[^0-9]" matches any three-character string starting with "Pa" and
ending with anything except a digit.
You can use a literal hyphen, caret, or square bracket in a set or class. The carat is treated as
special only if it is the first character after the left bracket (in any other place it is treated
literally). The hyphen is treated literally if it is either the first character (or second, if the carat
is the first character), or last character in the set. The right bracket is treated literally (not
special) if it is the first character (or second, if the carat is the first character) in the set.
- (hyphen)
This character has no special meaning outside of a set or a class.
. (period)
This character matches any single character.
Thus "S.m" matches "Sam", "Sbm", "Scm", etc. A period can be followed by "*" to mean zero
or more occurrences of any character, by "+" to mean one or more occurrences of any
character and by "?" to means zero or one occurrences of any character.
\
A backslash followed by any character matches that literal character.
For example, "Sam\." matches "Sam." unlike the expression "Sam.", which matches any four
character string starting with "Sam" because '.' matches any character. To use a literal
backslash character, enter it twice: "\\".
^
The caret matches the beginning of a field.
Thus "^Sam" matches the string "Sam" only when it is at the beginning of a field. For example,
"^am" matches "amplitude" but not "example".
$
The dollar sign matches the end of a field.
Thus "Sam$" matches the string "Sam" only when it is at the end of a field. For example
"am$" matches "slam" but not "tramp". To match a literal dollar character, use "\$". To match
a blank field, use "^$".
Note The use of back references in regular expressions is not permitted.
Literal Values of Special Characters
To use the literal value of a special character within a regular expression, you must precede
the special character with a backslash: "\". For example, to enter a literal backslash, you
must type it twice " \\". To enter a literal dollar sign, you must type backslash and then
dollar sign: "\$".
11
Set off regular expressions from the rest of the code with quotes. This enables you to use
variables, such as field names, and the Chr() function inside the regular expression.
It may not always be clear whether you are using a regular expression or a literal string.
The way to tell which is being used is by the context. Regular expressions can only be used
in the context of the Sub() and Gsub() functions and the "~", "!~" and Like operators.
Example 1
Compare:
If FieldAt("/SOURCE/R1/Field1") == "top"
with:
If FieldAt("/SOURCE/R1/Field1") ~ "top"
The "==" statement is only true if Field1 is "top".
The "~" statement is true if Field1 contains the string "top", so "top", "stop", and "topic"
are all true.
Example 2
Compare:
StrReplace("Mr.", "Mister", FieldAt("/SOURCE/R1/Field1"))
with:
GSub("Mr.", "Mister", Fields("/SOURCE/R1/Field1"))
These two expressions have identical syntax, but are different functions. The GSub()
function recognizes special characters. StrReplace() does not.
The StrReplace() expression finds the literal string abbreviation "Mr." in Field1 and
replaces it with the full word "Mister".
Because "." is a special character in regular expressions, the GSub() expression replaces
any string in Field1 that starts with "Mr" and has one more character after it, such as "Mrs"
or "Mrk", with the word "Mister"..
Functions and Operators
The following functions support the use of regular expressions:
• GSub Function (globally substitute)
• Sub Function (substitute)
The following operators allow the use of regular expressions:
• ~ Operator (contains)
12
Scripting in Data Integrator
• !~ Operator (does not contain)
• Like Operator - supports a limited set only
Escaping Hex Values
Example 1
This example checks to see if the field F1 contains, at the beginning of the field, an empty
square symbol.
FieldAt("/SOURCE/R1/F1") ~ "^\xFF"
The "\x" before the hex value "FF" indicates that the following two characters are a hex
value and should be evaluated together.
Example 2
You might attempt to use this expression to look for a square bracket ( [ ):
FieldAt("/SOURCE/R1/F1") ~ "\x5b"
However, this expression generates an error, because the hex escape is processed BEFORE
the entire expression is evaluated. Since the square bracket is a special character, a
matching bracket must follow it. If there is no closing bracket, an error occurs.
Caution You cannot use the hex value for a character that is already a special character.
Example 3
This expression looks for a lowercase y.
FieldAt("/SOURCE/R1/F1") ~ "\x79"
See Also
StrReplace Function
GSub Function
To learn more about regular expressions, see http://gnosis.cx/publish/programming/
regular_expressions.html.
Literal Values in Expressions
Literal values (constants) are exact values (alphabetic or numeric). These values are also
the constants that you use in expressions, such as the numeric value 100, or the string
"John Smith".
13
You must enclose literal text within quotation marks. The only exception to this rule is in
the Recognition Rules definition. In this case, literals are not enclosed in quotes, but
regular expressions are enclosed in quotes.
See Also
Recognition Rule Operators
For special handling of real dates versus text dates, see Managing Dates.
14
Script Editor
Script Editor
The Script Editor is the interface for creating and managing EZscript expressions. Each
element in the Script Editor provides tooltips to explain what the button or link is used for.
Many of the tooltips for Globals and Functions also provide usage examples.
You can use the Script Editor to:
• Add an expression to a target field in Map Designer
• Add or modify EZscript Expression artifacts from Design Manager
Exploring the Script Editor Window
The Script Editor window is composed of the following areas:
• Toolbar
Contains buttons to manage, edit, and validate your script.
• Expression area
Portion of the window where you will type your expression. You can customize the
display of the Expression area and insert certain functions, objects, and operators by
using the various features in the Script Editor window.
• Operators
Inserts operators into the expression at the current position of the cursor.
- If you have text selected when you select an operator, that text is overwritten.
- The Comment Out button applies C-style commenting to the entire highlighted
block instead of overwriting it. See Commenting Out Code.
• Fields
Contains a list of source fields mapped to the current field. This area appears only
when you open Script Editor from the Map Designer window.
• Globals
Provides quick access to the properties, methods, and operators for global objects,
macros, and variables.
• Functions
List of available EZscript functions organized by type.
• Validation Errors
When you click Validate Expression in the toolbar, validation errors appear at the
bottom of the Script Editor window.
15
Using the Script Editor
The following examples illustrate situations where you might use different features of the
Script Editor
• If you are writing a long script, the Show Line Numbers and Show Alternating Row
Colors buttons on the toolbar may make it easier to read.
• The code in the Expression area is color-coded to differentiate between the code
elements.
Note Script Editor displays deprecated functions with brown highlighting. Select an alternative
function when this occurs.
• When you insert code by selecting it in the Functions area, it includes proper syntax
for parameters or options.
16
Managing EZscript Expressions and Libraries
Managing EZscript Expressions and Libraries
This section includes the following topics:
• EZscript Expressions
• EZscript Libraries
See Also
Script Editor
Scripting in Data Integrator
Function Builder
EZscript Expressions
Script Editor allows you to write scripts to use with processes. After you add an EZscript
expression, you can add it to processes wherever Data Integrator offers a list of existing
expressions.
You can access Script Editor from several locations in Data Integrator. Design Manager is
the most convenient place to access the editor. To import an existing EZscript expression,
see Importing a Single File or Artifact.
>> To add an EZscript expression from Design Manager
1
In Design Manager, select the desired project.
2
Select the Add icon.
3
From the list, select EZscript Expression.
4
Enter a name for the expression and click Open Designer. Script Editor opens.
5
Enter your expression.
Note After you press Enter or the spacebar, reserved words are highlighted.
6
To check for syntactical errors, click the Validate icon. Address any errors in your script.
7
Once the expression is valid, save it.
17
Note Validate checks for proper syntax only. Your expression logic is validated at runtime, not
when validating with Script Editor. This means that if you try to pass a function that is not
supported, the error is apparent. If you add an unsupported function to a script, the error is
written to the log.
See Also
When you launch Script Editor from the Process window, a Steps panel is available for
building Decision step expressions. For information on using the Steps panel, see Building
Decision Step Expressions.
EZscript Libraries
An EZscript library is an artifact containing reusable functions or subroutines. Create
EZscript libraries with Script Editor and call them from maps and processes. You can also
import existing script files into EZscript libraries. For details on importing artifacts, see
Importing a Single File or Artifact.
This section contains the following topics:
• User-Defined Functions
• Adding EZscript Libraries
• Accessing EZscript Libraries
User-Defined Functions
Store user-defined functions in your EZscript libraries to help create complex expressions.
Keep the following in mind when preparing to create user-defined functions:
• The End function statement is necessary for the integration tools to recognize the end
of a function.
• The function name must be unique and NOT the same as any reserved words or
function names (for example, Add1Part function).
• Assigning a value to the function is treated exactly the same as a Return Statement. If
you assign a value to the function, it immediately returns the value assigned. Because
of this, you can only assign one value to a function. So instead of assigning multiple
values, assign the values to a variable.
• The number of parameters set in the declaration must be the number of parameters
passed when calling the function. For a map to return a value, the function name must
be set to the return value.
• While you can declare user-defined function parameters as ByVal, they are passed
ByReference. Data typing is not allowed.
18
Managing EZscript Expressions and Libraries
• If you want to use a library thoughout a map or process, make sure to declare the
function as Public.
Public Function myFun(var,var2)
'body goes here
End Function
• Use a Script step or Start step to call an EZscript Library in a process.
• Access libraries as described in Using EZscript Libraries in Processes and Using EZscript
Libraries in Maps. Alternately, declare and call the library in an expression:
Include "C:\MyCodeModule.ezscriptlibrary"
Note The string MUST be hard-coded in the script.
Example
Function ThreePartNum(X,Y,Z)
if IsNull(Y) Or IsNull(Z) then
X=0
Y=0
Z=0
End If
X = Cdbl(X)*65536*65536
Y = Cdbl(Y) * 65536
Z = Cdbl(Z)
ThreePartNum = Parse(1, str(cdbl(X + Y + Z)), ".")
End Function
Example Containing a Value Assigned to a Variable
‘Assign values to a variable and then return the variable
function x()
dim y
y = 1
y = 2
return y
end function
19
Adding EZscript Libraries
>> To create an EZscript library artifact
1
In Design Manager, select the desired project.
2
Select the Add icon.
3
From the list, select EZscript Library.
4
Enter a name for the library and click Open Designer. Script Editor opens.
5
Add your functions and subroutines.
Note After you press Enter or the spacebar, reserved words are highlighted.
6
Save your library.
Accessing EZscript Libraries
>> To access an EZscript library in a map or process
1
From the Map window or Process window, select the View menu, then select Globals.
2
Click the Libraries tab.
3
Select a library, then click the arrow pointing to the right. The selected library is now
available to use in the map or process.
Note If your EZscript library contains user-defined functions, the library is available from Script
Editor to add to any new expression. Locate the library under the Globals column in the UserDefined Functions list.
20
Using Scripts to Perform Specific Tasks
Using Scripts to Perform Specific Tasks
This section includes the following topics:
•
•
•
•
•
Specifying Ranges in Expressions
Managing Dates
Validating Data Types in Expressions
Capturing Transformation Metadata
Handling Invalid Data
Specifying Ranges in Expressions
You can write expressions used in filters to specify ranges. The three categories you can
use are numeric, text, and date formats. To convert records where field contents fall within
certain parameters, look at the following examples.
Example of Specifying a Numeric Range
This example converts records of customers where the balance falls within a certain range.
The source field type is numeric.
FieldAt("/SOURCE/R1/Balance")>= "150.00" And FieldAt("/SOURCE/R1/
Balance") <= "2500.00"
Example of Specifying a Text Range
This example interprets the field data as numeric instead of text by using the Val function.
The source field type is text.
Val(FieldAt("/SOURCE/R1/Balance")) >= "150.00" And Val(FieldAt("/
SOURCE/R1/Balance")) <= "2500.00"
Example of Specifying a Date Range
This example converts only records where the date falls within a specified range. The
source field type is date.
DateValue(FieldAt("/SOURCE/R1/Date")) >= "01/01/94" And
DateValue(FieldAt("/SOURCE/R1/Date")) <= "12/31/94"
Managing Dates
Use scripting to manipulate dates in a variety of ways:
• Converting Dates
19
•
•
•
•
Using Masks to Convert Two-digit Dates
Avoiding Truncating Data
Setting Up Picture Masks
Filtering by Date
Converting Dates
Dates may appear in a wide variety of formats in data files. This table gives you source,
target, and data type details, and what to do to convert dates for each type.
Source and Data type
Target and Data type
To Convert Dates
Pre-structured
Pre-structured
Data type is "Date"
Data type is "Date"
Maps usually convert dates to the correct format
in the target file automatically. If not, re-format
the date.
Delimited ASCII
Pre-structured
Data type is "Text"
Data type is "Date"
Binary, Fixed ASCII, or
Record Manager
Pre-structured
Write a target field expression to re-format the
date in your target date field.
Any type
Binary, Fixed ASCII, or
Record Manager
Write a target field expression to re-format the
date in your target date field.
Write a target field expression using the
DateValMask function. See DateValMask Function.
Many prestructured data files allow dates to be stored in only one format. For example,
dBASE applications store dates in an "yyyymmdd" format. Binary and record manager data
files may store dates as integers. Spreadsheets and ASCII files may contain dates formatted
as "mm/dd/yy", "yy/mm/dd", "dd-mon-yyyy", or any of the other unlimited possibilities.
Therefore, when converting dates from one application to another, some special handling
may be required.
There are several functions for manipulating dates:
•
•
•
•
•
•
•
•
•
20
CDate Function
Date, Date$ Functions
DateAdd Function
DateConvert Function
DateDiff Function
DatePart Function
DateSerial Function
DateValue Function
DateValMask Function
Using Scripts to Perform Specific Tasks
• IsDate Function
For a complete list of available functions, see Functions.
This table gives examples for date transformation expressions.
Source Format
Target Format
Expression Example
Text field
Text field
dd-mon-yy mm/dd/
yy
05-Jul-99 05/07/99
DateConvert("dd-mon-yy ", "mm/dd/yy",
FieldAt("/SOURCE/R1/Field1"))
Two Text fields, one
date, the other time:
SQL Server DateTime
fields
Field1:
Field1:
09/15/99
09/15/99
Field2:
Field2:
14:37:09
14:37:09
Date Field from SQL
Server table
To Binary Packed
decimal
No date conversion expression is necessary. Using the
default expression, a target field is converted to the date
value as a packed decimal.
dBASE Date field
Text field
yyyymmdd
mm/dd/yy
DateConvert("yyyymmdd", "mm/dd/yy",
FieldAt("/SOURCE/R1/Field1"))
19980122
01/22/98
Text field
Text field
mm/dd/yy
mm/dd/yyyy
DateValMask(FieldAt("/SOURCE/R1/Field1")
& (FieldAt("/SOURCE/R1/Field1")), "mm/dd/
yyH24:MM:SS")
If Right(FieldAt("/SOURCE/R1/Field1"), 2) >=
50 Then
Left(FieldAt("/SOURCE/R1/Field1"), 6) & "19"
& Right(FieldAt("/SOURCE/R1/Field1"), 2)
Else
Left(FieldAt("/SOURCE/R1/Field1"), 6) & "20"
& Right(FieldAt("/SOURCE/R1/Field1"), 2)
End if
The last expression example above checks for a year value greater than 50, concatenates
"19" if the year is more than 50, and concatenates "20" if less than 50. It is used to
transform two-digit dates into four-digit ones. The 50 can be replaced with whatever
number your company uses as the cut-off for year 2000 data conversions. It can also be
varied according to what is logical for each field. For example, a birth date field would
21
almost always need "19". An expiration date on a 10-year warranty field would be more
likely to need "20".
Note The mask for three letter months, like Feb, is "Mon" for the DateValMask function, and
"mmm" for the Format function. See DateValMask Function.
Date masks are lowercase and time masks are uppercase. MM indicates a two-digit
minute; mm indicates a two-digit month.
Using Masks to Convert Two-digit Dates
This section relates to situations where the source file contains date values with a twodigit year. Two-digit years are frequently found in legacy systems stored in ASCII, COBOL,
or other binary data formats. Any time you need to convert two-digit year, use a date mask
or an expression similar to the ones below.
By default, the three most commonly used date conversion functions, DateConvert,
DateValue, and DateValMask, use the workstation system date to set the century when
converting two-digit to four-digit dates. This means that if the system date is 1999, these
functions adds a 19 unless you specify otherwise in an expression like the one below. If the
system date is 2000, these functions add a 20 to the two-digit input date unless you specify
otherwise in an expression like the one below. You can also use the new mask type for twodigit dates, as described below.
Regarding Year 2000 date conversion, no assumptions are made as to what you want to do
with dates. Mapping does not impose any standard for where to split the dates that may
or may not work for your data needs. Instead, you can use expressions to manipulate your
data as you see fit.
Mask Type for Two-Digit Dates, "YYdddd"
Use the format YYdddd in functions that employ a mask, such as DateValMask or
DateConvert. For example, use it in Y2K conversions by specifying the century split to be
automatically applied.
Note Use the DateConvert mask as the source format, not the target format.
Syntax Notes
dd dd
22
Using Scripts to Perform Specific Tasks
Is a four digit (or less) value used to specify the base century and the century split. The
right-most two digits are used to indicate the split and the left-most digits indicate the
base century.
Example 1
Date mask "YY1900/mm/dd"
Specifies that all of the dates are in the range of 1900/01/01 to 1999/12/31. The base
century is 1900 and all two-digit years are mapped into the base century.
Date mask "YY1950/mm/dd"
Indicates that all two-digit years starting with 50 are mapped into the 1900s. The two-digit
years less than 50 are mapped into the next century (2000s).
Date mask "YY1970/mm/dd"
Similar mapping as above, but the split starts for years less than 70.
Note If no numeric value follows the "YY", then the base century is 0 and there is no split. If
the numeric value is greater than 9900, then the base century is also treated as 0. All other
values between 0 and 9900 work as described above.
Example 2
Below is an example of an expression that manipulates dates using the "50 / 51" standard.
The date mask in the source file is "mm/dd/yy" or "mm-dd-yy", and both the source and
target data types are Text.
If Right(FieldAt("/SOURCE/R1/Field1"), 2) >= 50 Then
Left(FieldAt("/SOURCE/R1/Field1"), 6) & "19" & Right(FieldAt("/
SOURCE/R1/Field1"), 2)
Else
Left(FieldAt("/SOURCE/R1/Field1"), 6) & "20" & Right(FieldAt("/
SOURCE/R1/Field1"), 2)
End if
This expression checks for a year value greater than or equal to 50, concatenates "19" if
the year is more than 50, or concatenates 20 if less than 50. It is used to transform twodigit text dates into four-digit text dates. The 50 can be replaced with whatever number
your company uses as the cut-off for Year 2000 data conversions, or whatever number
seems appropriate for the data in that particular field. An expiration date field, for
example, would be likely to need a different cut-off number than a birthdate field.
23
Avoiding Truncating Data
If converting to a text field, make sure the size of the target field is large enough to
accommodate the extra two characters. If the target is a date field, you must use the
DateValue or the DateValMask function. See the following examples for how the source
type data can be transformed into the target type result.
Example 1
Source type: Text
Source data: 11/22/98 and 12/22/45
Converting a standard formatted text date to an Access DateTime field with 50 as the cutoff:
If Right(FieldAt("/SOURCE/R1/Field1") , 2) >= 50 Then
DateValMask(Left(FieldAt("/SOURCE/R1/Field1") , 6) & "19" &
Right(FieldAt("/SOURCE/R1/Field1") , 2), "mm/dd/
yyyy")ElseDateValMask(Left(FieldAt("/SOURCE/R1/Field1") , 6) & "20"
& Right(FieldAt("/SOURCE/R1/Field1") , 2), "mm/dd/yyyy")
End if
Result: Access DateTime/ 11/22/1998 and 12/22/2045
Example 2
Source data: 5-digit Julian date/ 99360 and 36277
Converting a Julian date with two digit year and three-digit day of the year with 40 as the
cut-off:
If Left(FieldAt("/SOURCE/R1/Field3") , 2) >= 40 Then
Left(DateConvert("yyddd", "mm/dd/yy", FieldAt("/SOURCE/R1/Field3")
) , 6) & "19" & Right(DateConvert("yyddd", "mm/dd/yy", FieldAt("/
SOURCE/R1/Field3") ) , 2)ElseLeft(DateConvert("yyddd", "mm/dd/yy",
FieldAt("/SOURCE/R1/Field3") ) , 6) & "20" &
Right(DateConvert("yyddd", "mm/dd/yy", FieldAt("/SOURCE/R1/
Field3") ) , 2)
End if
Result: Text/ 12/26/1999 and 10/03/2036
Example 3
Source type: Text
Data: 980409 and 640722
24
Using Scripts to Perform Specific Tasks
Converting unformatted text date with year first to an access date with 70 as the cut-off:
If Left(FieldAt("/SOURCE/R1/Field5") , 2) >= 70 Then
DateValMask("19" & Left(FieldAt("/SOURCE/R1/Field5") , 2) &
Right(FieldAt("/SOURCE/R1/Field5") , 4),
"yyyymmdd")ElseDateValMask("20" & Left(FieldAt("/SOURCE/R1/
Field5") , 2) & Right(FieldAt("/SOURCE/R1/Field5") , 4),
"yyyymmdd")
End if
Result: Access Date Time/ 04/09/1998 and 07/22/2064
See Also
Managing Dates
DateConvert Function
DateValue Function
DateValMask Function
Filtering by Date
It is common to convert selected records based on a date or dates in a field. For example,
you may run a transformation on a daily basis and only want to transform those records
that contain today's date. Dates may appear in a wide variety of formats in data files, such
as the following:
• Type of data file - Pre-structured data files where dates are stored in only one format,
such as dBASE; binary files; record manager files; spreadsheets; ASCII files
• Typical date format - "yyyymmdd" (stored as a "Date" type); "Text", "Integer", or
"Date" types; "mm/dd/yy", "yy/mm/dd", or "dd-Mon-yyyy"
Example of Filtering Two or More Date Fields
Both fields are defined as Date. In this case, you only want records that contain
"19941215" in ("FIELD1") and "19940915" in ("FIELD2").
DateValMask(FieldAt("/SOURCE/R1/Field1"), "yyyymmdd") = "19941215"
And DateValMask(FieldAt("/SOURCE/R1/Field2"), "yyyymmdd") =
"19940915"
25
Example of Filtering Records Based on the Date in a Single Field
The field is defined as Text, where the source type is a Fixed ASCII file, and where you only
want records that contain dates between "05/01/1994" and "05/05/1994", inclusive, in
("FIELD1").
DateValue(Trim(FieldAt("/SOURCE/R1/Field1"))) >=
DateValue(Trim("05/01/1994")) And DateValue(Trim(FieldAt("/SOURCE/
R1/Field1"))) <= DateValue(Trim("05/05/1994"))
Example of Filtering Records Based on Dates in Two Fields
The fields are both defined as Date, where you want only records where the contents of
Field1 are greater than or equal to the contents of Field2.
Write this record expression:
FieldAt("/SOURCE/R1/Field1") >= FieldAt("/SOURCE/R1/Field2")
See Also
Managing Dates
Setting Up Picture Masks
The Picture Mask option designates special data formatting, such as how Date, Time, Date/
Time, and Boolean data is stored in your source data file or table.
Date formats must be entered using lower case letters, as in mmyydd.
26
Token Name
Description
True.False
Returns a true or false value
Yes.No
Returns a yes or no value
d
day of month (1 - 31)
dd
day of month (01 - 31)
ddd
day of the year (001-365, 366 in leap year)
m
Month number (1 - 12)
mm
Month number (01 - 12)
mon
Abbreviated month name
month
full month name
Using Scripts to Perform Specific Tasks
Token Name
Description
yy
last two digits of year (00 - 99)
yyyy
full year
HH
hour (am/pm)
H24
hour (military, 0 - 23)
MM
minutes (00 - 59)
SS
seconds (00 - 59)
TTx
Thousandths. "x" is the number of digits. If missing, 3 is used.
Am
AM/PM indicator. Not case-sensitive. Must be preceded by HH, MM, or
SS.
Note When using tokens to specify a mask as an argument in a function, you must quote the
mask such as "mm/dd/yyyy".
Validating Data Types in Expressions
When using character-based source connectors (ASCII, XML, spreadsheets) with strongly
typed target connectors (databases, binary), it is important to include data validation
functions in your mapping expressions.
You can interpret data typing errors that occur by using functions or error handing
statements that halt your transformation. Without these measures, hard-to-interpret
errors may occur, such as no data being returned to the target file or table.
Example
Source: ASCII (Delimited) with fields that contain date and number values
Target: SQL database with fields containing Date/Time and 16-bit Integer data types
In this case, check the source values to make sure they can successfully be represented in
those formats. Here are two methods to do this:
• Use functions to test your data - Functions such as IsDate and IsNumeric can help
determine whether or not character data can be represented as another data type.
27
• Set up an error handler - You can use the On Error Go To statement to setup an error
handler. Next, use one of the explicit conversion functions, such as CBool, CByte,
CDate, CDbl, CInt, CLng, CSng. Character data that cannot be represented in the target
data type results in an expression error and is caught by the error handler. This makes
it easier to understand why the conversion was not successful.
Tip Always explicitly validate data when converting between two different data types,
such as 32-bit integer to 16-bit integer, or when converting between different source/
target connectors where data types have disparate maximum/minimum values.
Capturing Transformation Metadata
Use DJImport and DJExport objects to access transformation metadata. Certain sources
and targets, including intermediate targets, like lookups and rowsets, and DMS
connectors, cannot be accessed this way.
Remember to use absolute paths when referencing files on other machines.
For the available properties, see Object Properties.
Retrieving Source and Target Metadata
These functions demonstrate capturing information about the source and target for the
transformation.
Filename Example
The Filename function returns the file name, including the drive and directory path, of the
source in this transformation:
Sources("SOURCE").Filename
This expression returns:
"C:\TestData\MyData\tutor1.asc"
If you only want to return the file name (without drive and directory path), use this inside
the Parse function as follows:
Parse(4, Sources("SOURCE").Filename, "\")
This expression returns:
"tutor1.asc "
If the source is a database, this function returns null. See Parse Function.
28
Using Scripts to Perform Specific Tasks
Database Example
This example returns the database name of the target in this transformation:
Targets("TARGET_1").Database
This expression returns:
"imqdb"
If the target is a file-based connector, this function returns null. See Parse Function.
Properties Example
The Properties function returns source or target properties values.
For instance, this example returns properties that you set in transformations.
Add the following code to a BeforeTransformation event:
FileWrite("outputfile", "Header = " &
Sources("SOURCE").Properties("Header"))
After running the transformation, the file contains:
"Header = True"
Using DJRecord and DJField Objects to Access Metadata
Refer to a DJRecord object by entering RecordAt("/SOURCE/recordname"). For details on
this object, see DJRecord Object Type.
Refer to a DJField object by entering FieldAt("/SOURCE/recordname/fieldname"). For
details on this object, see DJField Object Type.
Name Example
This example returns the name of a field:
FieldAt("/SOURCE/R1/FieldName").Name
FieldCount Example
This example returns the number of fields in a record:
RecordAt("/SOURCE/R1").FieldCount
TypeName Example
This example returns the data type of a field:
FieldAt("/TARGET_1/R1/FieldName").TypeName
29
Field Contents Example
This example returns the contents of a field:
FieldAt("/SOURCE/R1/FieldName").Value
Field Length Example
This example using the DJField object returns the field length values:
logmessage("info", "src.AcctNo.length = " & FieldAt("/SOURCE/R1/
Account No").length)
CurrentRecordType Example
This example returns the record type of a source:
RecordAt("/SOURCE/R1").currentrecordtype
Note This is not valid on targets, except when using the DJImport object variable.
Handling Invalid Data
When designing a transformation, it is often essential to validate your data before it is
mapped to your target. You can do this using the RecordStarted event. By executing a
validation at this point, you can reject the record or force the transformation to terminate
upon encountering invalid data, before running the OutputRecord action.
Validation statements can vary depending on your source and target data types, and the
rules you want to apply.
Examples
If you have a target field named "Account No" that must be numeric and five bytes in
length, your data validation statement is:
If IsNumeric(FieldAt("/SOURCE/R1/Account No")) Then
If Len(Trim(FieldAt("/SOURCE/R1/Account No"))) <> 5 Then
Reject()
Else
Val(FieldAt("/SOURCE/R1/Account No"))
End If
Else
Reject()
End If
30
Using Scripts to Perform Specific Tasks
Or, if you want to be certain that the incoming field is not blank, and notify the user of a
blank field, your validation statement is:
If IsNull(FieldAt("/SOURCE/R1/State")) Then
LogMessage("Target field 'State' must contain a value.")
Terminate()
End If
Or, if you want to process only records from customers in Texas, your validation statement
is:
If FieldAt("/SOURCE/R1/State") <> "TX" Then
Reject()
End If
31
32
Function Builder
Function Builder
Function Builder assists you in writing valid expressions by providing the syntax for all
available functions. This section includes the following tasks:
• Creating Functions in Function Builder
• Nesting Functions in Function Builder
• Adding Parameters to Functions
See Also
For a complete list of functions, along with their descriptions and examples of usage, see
Functions.
For information on setting function scope, see Setting the Scope of Functions.
Creating Functions in Function Builder
>> To create a function using Function Builder
1
From within Script Editor, click the Function Builder icon. Function Builder opens.
2
Select one of the following function categories:
-
Conversion
Date and Time
File and Directory
Math
Miscellaneous
Parse
Text
3
Select the desired function within the category. The definition of the function appears
below the category.
4
Enter any additional parameters.
5
Click Save to enter the syntax into Script Editor.
Nesting Functions in Function Builder
At times, you may want to create a nested function from Function Builder. For each nested
function you create, you must relaunch Function Builder.
33
Note This task outlines building a simple nested function. Use as many levels as needed to
build your particular nested function.
>> To nest functions
1
Open Function Builder.
2
Select a function category and the desired function.
3
Instead of entering a value, click Build Function. Note that the title of the Function
Builder window updates to reflect the current level of nesting.
4
Select a second function category and associated function.
5
Enter a value for the second function.
6
Click Save.
7
Click Save again to exit Function Builder and enter the nested function into Script
Editor.
Example
1
Select Math as the function category, then select Abs as the function.
2
Click Build Function.
3
Select Math as the next function category, then select Rnd as the second function.
4
In the Value column, enter the following:
-254.362
5
Click Save twice. The following function appears in Script Editor.
Abs(Rnd(-254.362))
Adding Parameters to Functions
You can add additional parameters to certain functions in Function Builder.
>> To add a parameter
1
Open Function Builder.
2
Select a function category and the desired function. If a function can have additional
parameters, an Add icon appears in the appropriate Name column.
3
Click the Add icon
34
. An additional row with the parameter appears.
Functions
Functions
This section includes information on setting the scope of functions, as well as details on
each of the available functions.
Use Ctrl+F to search this list:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Setting the Scope of Functions
Abort Function
Abs Function
Add1Fmt Function
Add1Part Function
Add2Part Function
Asc Function
B64Decode Function
B64Encode Function
Bin Function
CBool Function
CByte Function
CDate Function
CDbl Function
CDec Function
CStr Function
ChangeDirectory Function
ChangeFromUnicode Function
ChangeToUnicode Function
CharCount Function
Choose Function
Chr, Chr$ Functions
CInt Function
Clean Function
ClearMacro Function
CLng Function
CreateObject Function
CSng Function
CurDir Function
35
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
36
Date, Date$ Functions
DateAdd Function
DateConvert Function
DateDiff Function
DatePart Function
DateSerial Function
DateValMask Function
DateValue Function
Day Function
DefineMacro Function
DeleteMessage Function
Discard Function
Environ Function
Eval Function
Exp Function
Extract Function
FieldAt Function
FileAppend Function
FileCopy Function
FileDateTime Function
FileDelete Function
FileExists Function
FileLen Function
FileList Function
FileRead Function
FileReadLine Function
FileRename Function
FileWrite Function
Filter Function
FindMessage Function
Fix Function
FlushLog Function
Format, Format$ Function
GetDirectory Function
Functions
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
GetObject Function
GetThreadID Function
GSub Function
Hex Function
Hour Function
IIf Function
InitCaps Function
InStr Function
InStrRev Function
Int Function
IsArray Function
IsDate Function
IsDirectory Function
IsFile Function
IsMacroDefined Function
IsNull Function
IsNumeric Function
IsObject Function
Join Function
LBound Function
LCase, LCase$ Functions
Left, Left$ Functions
Len Function
Log Function
Log10 Function
LogMessage Function
LTrim, LTrim$ Functions
LTrim, LTrim$ Functions
MacroExpand Function
MacroValue Function
MakeDirectory Function
Mid, Mid$ Functions
Minute Function
Month Function
37
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
38
NamePart Function
Now Function
Null Function
Oct Function
Parse Function
ParseXML Function
ParseXMLFile Function
Print Function
RecordAt Function
Reject Function
RemoveDirectory Function
Right, Right$ Functions
Right, Right$ Functions
Rnd Function
Round Function
RTrim, RTrim$ Functions
Second Function
Serial Function
Sgn Function
Shell Function
SignFlip Function
Sleep Function
SortArray Function
Space, Space$ Functions
Split Function
Str, Str$ Functions
StrComp Function
String, String$ Functions
StrReplace Function
StrReverse Function
Sub Function
Switch Function
Terminate Function
TestMask Function
Functions
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Time, Time$ Functions
TimeSerial Function
TimeValue Function
Transliterate Function
Transliterate Function
Trim, Trim$ Functions
UBound Function
UCase, UCase$ Functions
UTF8Decode Function
UTF8Encode Function
Val Function
ValMask Function
Weekday Function
Xlate Function
Year Function
Setting the Scope of Functions
To define a function available to an entire process, use the Public keyword:
public function xyzzy()
xyzzy="xyzzy"
end function
Substitute the Private keyword to create a function available only to the transformation or
process. Or use Dim to create a function only available in the current function module.
Note You cannot declare a variable in a module then call this variable in a user-defined
function from a different module. Instead, create a Private variable that is passed in and out of
the user-defined function.
Functions and local variables can be instantiated implicitly, just by using them, though this
does produce some potential problems, as follows:
Function foo()
b = 3
...
End function
39
b = 2
foo()
The variable b in function foo() is local to the function, and later comes into existence as a
private variable. This works as it should, but could be confusing. To get around this, the
Dim statement is supported (though in a restricted form, compared to Visual Basic). You
cannot declare a type, only that a variable exists.
Dim b
Function foo()
b = 3
...
End function
b = 2
foo()
After the function call, b contains 3, as expected.
To declare a private variable, just use Private in place of Dim. Once you define a public
function, it can be used anywhere you can use a function.
Note When debugging expressions, it is important to test functions before using them in other
fields.
Abort Function
40
Description
Causes the transformation to abort based on a specified condition.
Return
Not applicable; aborts the transformation
Return (Null)
Not applicable; aborts the transformation.
Syntax
Abort(number)
Parameters
This function has the following parameters:
Name
Description
number (optional)
Any valid numeric expression.
Functions
Remarks
Used in a conditional expression. If the number parameter is nonzero
(or if no number is supplied), this function sets a flag to abort the
transformation.
When an Abort is reached, no changes are applied to the target. Use
the Terminate Function instead if you want to apply changes to the
target and then continue with the process.
See Also
Terminate Function, Discard Function, and Reject Function
Example
The following expression converts the data in the ("Account_No")
field (along with the remainder of the mapped data. If the rightmost
character (digit) of the value in the ("Account_No") field is zero (0),
then the flag is reset and abort does not occur:
If Right(FieldAt("/SOURCE/R1/Account_No"),1) == 0
Then
Abort()
Else
FieldAt("/SOURCE/R1/Account_No")
End If
Abs Function
Description
Returns the absolute value of a numeric value
Return
Absolute value of the number referred in the expression
Return (Null)
Error: Incorrect argument count
Syntax
Abs(number)
Parameters
This function has the following parameters:
Remarks
Name
Description
number
Any valid numeric expression.
The absolute value of a number is the unsigned magnitude of the number.
The abs function returns a double value, if the argument is a floating point
value. If the argument is NOT a floating point value, then the return value
is an integer, and in that case is constrained by the bounds below:
Lower bounds: -2144967296
Upper bounds: 2144967296
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
41
See Also
Fix Function, Int Function, and Sgn Function
Example
Each of the following expressions evaluate the value to 33:
Abs(-33)
Abs(33)
Add1Fmt Function
Description
Formats (cleans) street address data to USPS standards
Return
Address field string formatted according to Post Office standards (U.S.)
Return (Null)
Error: Incorrect argument count.
Syntax
Add1Fmt(string)
Parameters
This function has the following parameters:
Name
Description
string
Any valid source field name, or any
valid string. If it is a string literal,
enclose in quotation marks.
Example: Add1Fmt(“12 Hall St”)
Remarks
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
See Also
Add1Part Function, Add2Part Function, NamePart Function, Parse
Function
Example
This example shows how to format the data in the source field Address1
to USPS standards:
Add1Fmt(FieldAt("/SOURCE/R1/Address1"))
Add1Part Function
Description
Splits (parses) a street address field
Return
Address parts, such as number, street name, suffix, etc., to a different field
or fields
Return (Null)
Error: Incorrect argument count.
Syntax
Add1Part(NU|PRD|SN|SU|POD|SAU|SAR, (string)|Field Name)
42
Functions
Parameters
This function has the following parts. If the string is a string literal, enclose
the string in quotation marks.
Part
Description
NU
Returns the street number
PRD
Returns the pre-directional
SN
Returns the street name
SU
Returns the suffix
POD
Returns the post-directional
SAU
Returns the secondary address unit
SAR
Returns the secondary address
range
REM
Returns the remainder
string
The search string from the source
file. It can be entered either as a
specific string, or as a field name. If
it is a string literal, enclose in
quotation marks.
Example: Add1Part("NU",
FieldAt("/SOURCE/R1/Address1"))
Field Name
Remarks
Source or target field.
When a field in the source file contains a street address, it is sometimes
desirable to split (parse) the full address into parts and write each part to
a separate field in the target file. See the Parameters table for a list of all
supported parts.
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
43
See Also
Add1Fmt Function, Add2Part Function, NamePart Function, Parse
Function
Example
To parse a street address field into separate fields in your target file,
where the entire street address is in one source field called ("Address1").
Each of the lines below is added in a separate target field expression:
Add1Part("NU", FieldAt("/SOURCE/R1/Address1"))
Add1Part("PRD", FieldAt("/SOURCE/R1/Address1"))
Add1Part("SN", FieldAt("/SOURCE/R1/Address1"))
Add1Part("SU", FieldAt("/SOURCE/R1/Address1"))
Add1Part Function Instructions
When your source data file contains one field that includes that includes the street
address, it is often necessary to write each part of the address to a separate field in your
target data file.
>> To parse a street address field
1
Open a map.
2
Insert one or more additional fields (depending on how you want the information to
be stored in the target file) in the desired position.
3
In this example, the source field that contains the whole street address is
("Address1"). The three fields in the target file that contain the address parts have
been given field names: Direction, Number, and Street. The target field expression in
each of the three fields has been written to instruct a map to place a specific address
"part" in that field in the target data file.
Target Field Name
Target Field Expression
Notes
Direction
Add1Part("PRD", FieldAt("/SOURCE/
R1/Address1"))
"PRD" places the pre-directional in
the Direction field
Number
Add1Part("NU", FieldAt("/SOURCE/R1/
Address1"))
"NU" places the street number in
the Number field
Street
Add1Part("SN", FieldAt("/SOURCE/R1/
Address1"))
"SN" places the street name in the
Street field
4
44
After the transformation is run, the street address in every record is parsed into the
three separate fields in the target data file.
Functions
Add2Part Function
Description
Splits (parses) an address field
Return
Address parts, such as city, state, zip, to a different field or fields
Return (Null)
Error: Incorrect argument count.
Syntax
Add2Part(c|s|z, (string)|Field Name)
Parameters
This function has the following parts. If the string is a string literal, enclose
the string in quotation marks.
Remarks
Part
Description
c
Returns city
s
Returns state
z
Returns zip. See note below.
string
This is the search string from the
source file. It can be entered either
as a specific string, or as a field
name: "Field1".If it is a string literal,
enclose in quotation marks.
Example: Add2Part("c" "Austin, TX,
78727")
Field Name
source or target field.
When a field in the source file contains a full city-state-zip address, it is
sometimes desirable to split (parse) the full address into parts (city, state,
zip) and write each part to a separate field in the target file.
Note: The zip code must be supplied in the standard 5-digit or 5-4 digit
format (e.g., 78727 or 78727-6418). Data in any other format is ignored.
See Also
Add1Fmt Function, Add1Part Function, NamePart Function, Parse
Function
Example
To parse an address field into separate fields in your target file, where the
city, state, and zip are in one field, called ("Address2") in the source file.
Each of the lines below is entered in a separate target field expression:
Add2Part("c", FieldAt("/SOURCE/R1/Address2"))
Add2Part("s", FieldAt("/SOURCE/R1/Address2"))
Add2Part("z", FieldAt("/SOURCE/R1/Address2"))
45
Add2Part Function Instructions
When your source data file contains one field that includes the city, state, and zip code, it
is often necessary to write each part of the address to a separate field in your target data
file.
>> To parse an address field
1
Open your map.
1
Insert an additional field or two (depending on how you want the information to be
stored in the target file) in the desired position.
2
In this example, the source field contains the whole address "Address". The three
fields in the target file contain the address parts and have been given field names: City,
State, and ZIP. The target expression in each of the three fields is written to instruct a
map to place a specific address part of the address in that field in the target data file.
Target Field
Name
Target Field Expression
Notes
City
Add2Part("c", FieldAt("/SOURCE/R1/
Address"))
"c" places the city in the City
field
State
Add2Part("s", FieldAt("/SOURCE/R1/
Address"))
"s" places the state in the
State field
ZIP
Add2Part("z", FieldAt("/SOURCE/R1/
Address"))
"z" places the zip code in the
ZIP field
After the map is run, the city, state, and zip code in every record are parsed into the three
separate fields in the target data file.
Asc Function
Description
Finds the first character in a string.
Return
ASCII code (not hexadecimal code) for the first character in a
string
Return (Null)
Error: Incorrect argument count.
Syntax
Asc(string)
Parameters
This function has the following parameters:
Name
46
Description
Functions
string
Any valid string expression. If
the string is a string literal,
enclose the string in quotation
marks. Asc(“string”).
Remarks
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Chr, Chr$ Functions
Example
Write the first letter of the source field ("First Name") to the
target field, and return the ASCII code for that character:
Asc("First Name")
B64Decode Function
Description
Converts a Base64 string
Return
Binary value when supplied with a Base64 string
Return (Null)
Error: Too few arguments.
Syntax
B64Decode(src, [encoding])
Parameters
This function has the following parameters:
Name
Description
src (required)
Contains the Base64 formatted
string to be decoded.
encoding [optional]
If you use the encoding parameter,
you are limited to DJENC_xxx
values. If the parameter is not set,
DJENC_OEM is used (uses the
current codepage).
For a list of all of the encoding
constants available for this
parameter, see the Encoding
Reference.
Remarks
To convert a string of binary values into Base64 format, use the B64
Encode function.
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
47
See Also
B64Encode Function, UTF8Encode Function, and UTF8Decode Function
Example
This expression converts "Field1" contents from Unicode UTF-8 encoding
into its original format:
B64Decode(FieldAt("/SOURCE/R1/Field1"), ENC_UTF8)
B64Encode Function
Description
Converts a string of binary values
Return
Base64 format when supplied with binary values
Return (Null)
Error: Too few arguments.
Syntax
B64Encode(src, [encoding])
Parameters
This function has the following parameters:
Name
Description
src (required)
Contains the string of binary
values to be encoded.
encoding (optional)
If you use the encoding
parameter, you are limited to
DJENC_xxx values. If the
parameter is not set,
ENC_OEM is used (uses the
current codepage).
For a list of all of the encoding
constants available for this
parameter, see the Encoding
Reference.
Remarks
To convert the Base64 string back to the original binary string, use
the B64 Decode function.
After conversion, the new Base64 string can be assigned to a target
field in an XML document, for example. B64 Encode/Decode
functions are useful for manipulating binary objects such as icons,
bitmaps, and audio files, etc.
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
48
Functions
See Also
B64Decode Function, UTF8Encode Function, and UTF8Decode
Function
Example
This expression converts "Field1" into Base64 format using Unicode
UTF-8 encoding (encodes string of values in Field1 into 8-bit
characters):
B64Encode(FieldAt("/SOURCE/R1/Field1"), ENC_UTF8)
Bin Function
Description
Converts a decimal into a binary string
Return
Equivalent binary string when supplied with a decimal value
Return (Null)
Error: Incorrect argument count.
Syntax
Bin (number)
Parameters
This function has the following parameters:
Name
Description
number (required)
Decimal to be converted into a
binary string.
Remarks
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Hex Function, Oct Function
Example
The following expression returns 1001001:
Bin (73)
CBool Function
Description
Coerces the result of a string, number, or expression to a Boolean data
type
Return
Boolean data type when supplied with a string, number, or expression
Return (Null)
Error: Incorrect argument count.
Syntax
CBool(string)
Parameters
This function has the following parameters:
49
Remarks
Name
Description
string
A number or an expression. If the
string is a string literal, enclose the
string in quotation marks.
CBool(“string”).
If the string expression evaluates to a nonzero value, CBool returns True
with a value of -1; otherwise, it returns False with a value of 0.
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
See Also
CByte Function, CDate Function, CDbl Function, CInt Function, CLng
Function, and CSng Function
Example
If Field1 contains data, this expression returns a value of –1 to indicate it
is True; if Field1 is blank, this expression returns a value of 0 to indicate it
is False:
CBool(Trim(FieldAt("/SOURCE/R1/Field1")))
Note: The Trim Function is added to remove any spaces that might be in
the field. Without Trim, the expression would return True (-1) if there
were one or more spaces in Field1. See Trim, Trim$ Functions.
CByte Function
Description
Coerces a number or numeric string into a Byte data type
Return
Byte data type when supplied with a number or numeric string
Return (Null)
Error: Incorrect argument count.
Syntax
CByte(n)
Parameters
This function has the following parameters:
Name
Description
n
Any valid integer expression with a
value between 0 (zero) and 255.
Remarks
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow. It may also return stack
underflow errors.
See Also
CBool Function, CDate Function, CDbl Function, CInt Function, CLng
Function, and CSng Function
50
Functions
Example
This example converts all numbers in source ("Field1") into a Byte data
type:
CByte(FieldAt("/SOURCE/R1/Field1"))
This example returns 255 to the target as a Byte data type:
CByte(255)
CDate Function
Description
Coerces the result of a valid date string or number to a Date data type
Return
Date data type when supplied with a date string or number
Return (Null)
Error: Incorrect argument count.
Syntax
CDate(datestring)
Parameters
This function has the following parameters:
Remarks
Name
Description
datestring
Any valid date string. If the
string is a string literal, enclose
the datestring in quotation
marks. CDate(“datestring”).
Use the DateValMask Function to define the date mask in your
expressions.
The date values “00/00/0000” or “00/00/00” are not valid for this
function. These values cause a type mismatch error.
See Also
CBool Function, CByte Function, CDbl Function, CInt Function, CLng
Function, CSng Function, and DateValMask Function
Example
This example coerces the source field ("Date") into a Date data type.
The DateValMask function is used to define the date mask of the
source:
CDate(DateValMask(FieldAt("/SOURCE/R1/Date"), "mm/
dd/yyyy"))
Note Salesforce.com users: When connecting to Salesforce.com, this function returns local
time instead of GMT. If needed, create another script (DateAdd for example) to shift the CDate
return value. A map can call the second script.
51
CDbl Function
Description
Coerces the result of a number or numeric string to a Double data
type
Return
Double date type when supplied with a number or numeric string
Return (Null)
Error: Incorrect argument count
Syntax
CDbl(number)
Parameters
This function has the following parameters:
Name
Description
number
Any number between
-1.79769313486232E308 to 4.94065645841247E-324 for
negative values, and
4.940645841247E-324 to
1.7976931348632E308 for
positive values. Enclose in
quotation marks.
Remarks
This function may throw errors for invalid characters, stack
overflows, and stack underflows.
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
See Also
CBool Function, CByte Function, CDate Function,CInt Function, CLng
Function, and CSng Function
Example
This expression coerces numeric strings in the source field ("Field1")
into Double data types:
CDbl(FieldAt("/SOURCE/R1/Field1"))
CDec Function
52
Description
Coerces the result of a number or numeric string to a Decimal data
type
Return
Decimal data type when supplied with a number or numeric string
Return (Null)
Error: Incorrect argument count
Syntax
CDec(number)
Functions
Parameters
Remarks
This function has the following parameters:
Name
Description
number
Any number between -10^58
to 10^58.
This function may throw an error for invalid input.
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
See Also
CBool Function, CByte Function, CDate Function, CInt Function, CLng
Function, and CSng Function
Example
‘This expression coerces numeric strings in the source field ("Field1")
into Decimal data types:
CDec(FieldAt("/SOURCE/R1/Field1"))
CStr Function
Description
Coerces a number or date expression to a String representation
Return
Type string when supplied with string, long, double, decimal or date
Return (Null)
Error: An Err_Nulll occurs.
Syntax
CStr(expr)
Parameters
This function has the following parameters:
Remarks
Name
Description
expr
Expression to evaluate.
If the parameter is not one of the types listed in Return above, a
ERR_TYPEMISMATCH error is returned.
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
See Also
CBool Function, CByte Function, CDate Function, CInt Function, CLng
Function, and CSng Function
Example
‘This expression coerces decimals in the source field ("Field1") into a
string data type:
CStr(FieldAt("/SOURCE/R1/Field1"))
53
ChangeDirectory Function
Description
Changes the current working directory from the original directory
name to the new directory name
Return
Not applicable for this function
Return (Null)
Not applicable for this function
Syntax
ChangeDirectory(directoryname)
Parameters
This function has the following parameters:
Remarks
Name
Description
directoryname
Name of the directory that you
want to designate as the
current working directory. If
the string is a string literal,
enclose the string in quotation
marks.ChangeDirectory(“direc
toryname”).
When using DOS commands, you may also include the drive letter
and change the drive as well as the directory winnt, as in the
following:
ChangeDirectory("c:\winnt")
Enclose directory names and paths in quotation marks.
See Also
MakeDirectory Function and GetDirectory Function
Example
This expression changes the current directory to TestFiles:
ChangeDirectory("C:\TestFiles")
ChangeFromUnicode Function
54
Description
Converts a string from Unicode using the specified encoding
Return
String value of a supplied Unicode value
Return (Null)
Error: Incorrect argument count.
Syntax
ChangeFromUnicode(stringvalue, encoding)
Parameters
This function has the following parameters:
Functions
Remarks
Name
Description
stringvalue
The string to convert. If the
string is a string literal, enclose
the stringvalue in quotation
marks.
ChangeFromUnicode(“string
value” encoding).
encoding
The value of the desired
encoding.
If you do not specify an encoding, the default of ENC_OEM is
used.
For a list of supported constant names, encodings, values and
descriptions, see Encoding Reference.
See Also
ChangeToUnicode Function
Search for “Unicode (Fixed)” and “Unicode (Delimited)” in the
documentation.
Example
‘This expression changes the string “Test123” from Unicode to
ANSI (default) encoding:
ChangeFromUnicode("Test123")
ChangeToUnicode Function
Description
Converts a string to Unicode using the specified encoding
Return
Unicode, when supplied with a string
Return (Null)
Error: Incorrect argument count.
Syntax
ChangeToUnicode(stringvalue, encoding)
Parameters
This function has the following parameters:
Name
Description
stringvalue
The string to convert. If the
string is a string literal, enclose
the string in quotation marks.
ChangeToUnicode(“string
value” encoding).
encoding
The value of the desired
encoding.
55
Remarks
If you do not specify an encoding, the default of ENC_OEM is
used.
For a list of supported constant names, encodings, values and
descriptions, see Encoding Reference.
See Also
ChangeFromUnicode Function
Search for “Unicode (Fixed)” and “Unicode (Delimited)” in the
documentation.
Example
This expression changes the string “Test123” from ANSI to UTF8 encoding:
ChangeToUnicode("Test123", UTF-8)
CharCount Function
Description
Counts the occurrences of a particular character in a string
Return
Number of occurrences of a particular character in a string
Return (Null)
Error: Incorrect argument count
Syntax
CharCount(c, string)
Parameters
This function has the following parameters:
Remarks
Name
Description
c (required)
Specify the character that you
want to count. If the string is a
string literal, enclose the string
in quotation marks.
string (required)
Specify a string that you want
to count. If the string is a string
literal, enclose it in quotation
marks. CharCount(c, “string”).
This function allows you to count the number of occurrences of
a particular character in a string. This is very useful in the Count
parameter of event handlers, and also in conjunction with other
functions.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
56
Parse Function
Functions
Example
This example returns the number of spaces in the first source
field:
CharCount(" ",FieldAt("/SOURCE/R1/Field1"))
The name “John Thompson Reynolds” would return 2.
This example returns the number of slashes ( / ) in a source field
named "Date":
CharCount("/",FieldAt("/SOURCE/R1/Date"))
6/9/98 would return 2.
This example uses CharCount combined with the Parse Function
to divide a field into it’s component parts based on dashes ( - ),
and return the last part. If the index is less than 1 or greater it
returns a null value.
Parse(CharCount("-", FieldAt("/SOURCE/R1/
Field8"))+1, FieldAt("/SOURCE/R1/Field8"), "-")
78765-2356 would return 2356.
Choose Function
Description
Selects a value from a list of values
Return
Value specified from a list of values of a specific type
Return (Null)
Error: Too few arguments.
Syntax
Choose(index, value1[, value2] . . .)
Parameters
This function has the following parameters:
Name
Description
index (required)
An integer value between 1 and the
number of value parameters.
value1 (required)
Specify the value you want to
translate.
value2(optional)
Additional value to translate. You can
add value3, value4, etc. See Remarks.
57
Remarks
The Choose function takes a variable number of parameters consisting of an
index parameter and a list of values as additional parameters. The maximum
number of values is 13.
Choose returns the parameter corresponding to the index as the function
result.
Choose can be used to select items from a predefined list or to translate
numeric codes into textual values.
Each value parameter passed to the Choose function is evaluated, regardless
of whether or not it is selected as the result. Care should be taken not to use
expressions that might cause undesirable side effects.
The Choose function returns null if index is less than 1, or if index is greater
than the number of value parameters in the parameter list.
Caution: This function returns a value that must be used or stored to prevent
stack overflow. See Stack Overflow.
See Also
IIf Function and Switch Function
Example
The following example translates color codes in the ("Color") field to color
names:
Choose(FieldAt("/SOURCE/R1/Color"), "Red", "Blue",
"Green")
This example uses the Weekday function to translate the contents of the field
("Date") into the names of the days of the week. The source file contains the
dates 12/01/03 through 12/05/03. The corresponding days Monday through
Friday are returned to the target:
Choose(Weekday(FieldAt("/SOURCE/R1/Date")), "Sunday",
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday")
Chr, Chr$ Functions
Description
Translates a single numeric character code to a Unicode character value.
Note: The Chr and Chr$ functions are interchangeable.
Return
Unicode equivalent of a one-character ASCII string
Return (Null)
Error: Incorrect argument count.
58
Functions
Syntax
'When n is a decimal value:
Chr(n)
'When NN is a hexadecimal value:
Chr(&h41)
Parameters
Remarks
This function has the following parameters:
Name
Description
n
Any valid integer expression with a
value 0 to 65,535 inclusive.
Chr$(034) in the first example below represents literal quotation marks.
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
See Also
Asc Function and Val Function
Example
To remove quotation marks in the source field named ("FIELDNAME")
write the following expression:
GSub(Chr$(034), "", FieldAt("/SOURCE/R1/FIELDNAME"))
'To get the character value of the hex number 41 use the following
expression. (This returns "A" minus the quotes):
Chr(&h41)
CInt Function
Description
Coerces the result of a number or numeric string to an Integer data type
Return
Integer data type equivalent of a supplied number or numeric string
Return (Null)
Error: Incorrect argument count.
Syntax
CInt(number)
Parameters
This function has the following parameters:
Name
Description
number
Any number between -32,768 and
32,767.
59
Remarks
Fractions are rounded. If the number happens to be exactly .05, then it is
rounded to the nearest even number.
Example: 0.5 is rounded to 0; 1.5 is rounded to 2.
Limitation: CInt supports values of 4 bytes or less.
This function differs from the Fix function or the Int function in that it
rounds rather than truncating the data.
This function may throw errors for invalid characters, stack overflows, and
stack underflows.
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
See Also
CBool Function, CByte Function, CDate Function, CDbl Function, CLng
Function, CSng Function, Fix Function, and Int Function
Example
This expression returns 234 in an Integer data type:
CInt(233.6557)
The expression below calculates phone call duration in hours, minutes
and seconds and determines the difference in seconds between the start
and end times 0217094349 and 0217094433. This expression is in total
number of seconds. To calculate that field into hours, minutes, and
seconds, you can write another expression in a separate target field:
CInt(FieldAt("/SOURCE/R1/Field10")) + 60 *
CInt(FieldAt("/SOURCE/R1/Field9")) + 3600 *
CInt(FieldAt("/SOURCE/R1/Field8"))) - CInt(FieldAt("/
SOURCE/R1/Field5")) + 60 * CInt(FieldAt("/SOURCE/R1/
Field4")) + 3600 * CInt(FieldAt("/SOURCE/R1/Field3")))
Clean Function
Description
Removes all nonprintable characters from a user-specified
string. The current language of the system determines what is
nonprintable. For example, a system that uses USA English ASCII
characters designates nonprintable characters as between 32
and 126 Decimal. Anything outside of this range would be
considered nonprintable on that system.
Return
Specified string with all nonprintable characters removed
Return (Null)
60
Syntax
Clean(string)
Parameters
This function has the following parameters:
Functions
Name
Description
string
The string from which you
want to remove all
nonprintable characters. If the
string is a string literal, enclose
the string in quotation marks.
Clean (“string”).
Remarks
See Also
Add1Fmt Function
Example
Clean("string")
ClearMacro Function
Description
Clears a macro that has been previously defined
Return
Not applicable for this function
Return (Null)
Error: Incorrect argument count.
Syntax
ClearMacro(macname)
Parameters
This function has the following parameters:
Name
Description
macname
Name of the macro you want
to undefine. If a string literal,
enclose in quotation marks.
ClearMacro(“macname”)
Remarks
See Also
DefineMacro Function, IsMacroDefined Function, MacroExpand
Function, and MacroValue Function
Example
Clears the definition of a macro previously defined as mymacro:
ClearMacro("mymacro")
61
CLng Function
Description
Coerce the result of a numeric string to a Long data type
Return
Long data type equivalent of a supplied number or numeric
string
Return (Null)
Error: Incorrect argument count
Syntax
CLng(number)
Parameters
This function has the following parameters:
Remarks
Name
Description
number
Any number between 2,147,483,648 and 2,147,483,647.
Fractions are rounded. If the number is exactly .05, then it is
rounded to the nearest even number.
Example: 0.5 is rounded to 1; 1.5 is rounded to 2.
This function differs from the Fix and Int functions, because it
rounds rather than truncates the data.
This function may throw errors for invalid characters, stack
overflows, and stack underflows.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
CBool Function, CByte Function, CDate Function, CDbl Function,
CInt Function, CSng Function, Fix Function, and Int Function
Example
This expression returns 880 in a Long data type:
CLng(879.7554)
Compare Function
62
Description
Compare two string arguments
Return
Value that represents the result of a comparison of two string
arguments
Return (Null)
Error: Too few arguments for function
Syntax
Compare("strexpr1", "strexpr2" [,[type])
Functions
Parameters
Remarks
This function has the following parameters:
Name
Description
"strexpr1" (required)
The first string argument.
"strexp2" (required)
The second string argument.
type (optional)
Specifies the string
comparison method. This
value must be 0 or 1. If
compare is 0, the string
comparison is case-sensitive. If
compare is 1, string
comparison is not casesensitive.
This function returns a value to indicate the relationship
between the string expressions. If strexpr1 is less than strexpr2,
-1 is returned. If strexpr1 equals strexpr2, 0 is returned. If
strexpr1 is greater than strexpr2, 1 is returned.
Tip: Compare and StrComp are interchangeable and identical in
syntax.
Be careful to observe case when using a function that performs
a string-search. String-search Functions are case-sensitive,
literal searches. A Function that searches for "x" disregards "X".
If the function has an optional parameter "compare", and you
do not use the optional compare parameter, the expression is
case-sensitive by default.
Caution: This function returns a value. The value must be used
or stored. Failure to do so causes a stack overflow. See Stack
Overflow.
See Also
StrReplace Function and StrComp Function
Example
This example compares "zip" and "ZIP" and requires the string
comparison to be case-sensitive by setting "(0)" as the compare.
It returns "1", since the text strings are mixed case:
Compare("zip", "ZIP", (0))
If a (1) compare is used in the expression above, a 0 is returned
to the target, indicating that the text strings are the same (casesensitivity is ignored).
63
CreateObject Function
Description
Creates and returns a reference to an ActiveX object
Return
Reference to the ActiveX object created
Return (Null)
Error: Incorrect argument count.
Syntax
CreateObject("objectname")
Parameters
This function has the following parameters:
Remarks
Name
Description
"objectname" (required)
Name of the object to create.
Enclose in quotation marks.
Every application that supports Automation provides at least
one type of object. For example, a word processing application
may provide an Application object, a Document object and a
Toolbar object. Once an object is created, you reference it in
code using the object variable you defined.
Use the CreateObject function when there is no current instance
of the object. If an instance of the object is already running, a
new instance is started, and an object of the specified type is
created. To use the current instance, or to start the application
and have it load a file, use the GetObject function. If an object
has registered itself as a single-instance object, only one
instance of the object is created, no matter how many times
CreateObject is executed.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
64
Functions
See Also
GetObject Function
Example
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Application.Workbooks.Open "c:\tutor1.xls"
xlApp.visible = True
x = xlApp.Application.Cells(1,1).Value
FileWrite("X: " & x)
"This is from Excel Cell (1,1): " & x
xlApp.Quit
Set xlApp = nothing
Return
End if
CSng Function
Description
Coerces the result of a number or numeric string to a Single data
type
Return
Single data type equivalent of a supplied number or numeric
string
Return (Null)
Error: Incorrect argument count
Syntax
CSng(number)
Parameters
This function has the following parameters:
Name
Description
number
Any number between 3.402823E38 and 1.401298E45 for negative
values, and 1.401298E045 to
3.402823E38 for positive
values.
65
See Also
CBool Function, CByte Function, CDate Function, CDbl Function,
CInt Function, and CLng Function
Example
This example coerces numeric strings in source ("Field2") into
Single data types:
CSng(FieldAt("/SOURCE/R1/Field2"))
CurDir Function
Description
Requests the current directory path
Return
String representing the current path
Return (Null)
String representing the current path, current working directory
Syntax
CurDir[(drive)]
Parameters
This function has the following parameters:
Remarks
Name
Description
drive (optional)
A string expression that
specifies an existing drive. If a
string literal, enclose in
quotation marks.
CurDir(“string”).
If no drive is specified, or if drive is a zero-length string (""),
CurDir returns the path for the current drive.
This function may throw errors for invalid characters, stack
overflows, and stack underflows.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
Example
Returns the current working directory on the C drive :
CurDir("C:\")
66
Functions
Date, Date$ Functions
Description
Requests the current system date
Note: The Date and Date$ functions are
interchangeable.
Return
Current system date
Return (Null)
Current system date
Syntax
Date[$]()
Parameters
No required parameters, however the
parentheses after the function name are
required.
Remarks
The Date and Date$ functions return different
formats of the current system date. Date
returns the current date as a date type value.
The value returned from Date$ is a formatted
string of the form mm-dd-yyyy.
Caution: This function returns a value that must
be used or stored to prevent stack overflow.
See Stack Overflow.
See Also
Format, Format$ Function, Now Function,
Time, Time$ Functions
Example
This expression returns the current system
date:
Date()
DateAdd Function
Description
Add or subtract a time interval to or from a date value
Return
Date representing original date with the interval added or subtracted
Return (Null)
Error: Incorrect argument count.
Syntax
DateAdd(interval, number, date)
Parameters
This function has the following parameters:
Name
Description
67
interval
A string expression describing the type of time
interval to add to the date argument. If a string
literal, enclose in quotation marks.
DateAdd(“string”) A list of valid time interval
strings is given below.
Time period
Interval value
Year
yyyy
Quarter
q
Month
m
Day of Year
y
Day of the Month
d
Day of the Week
w
Week
ww
Hour
h
Minute
n
Second
s
The intervals for Day of Year, Day, and Weekday
(y, d, and w) can be used interchangeably to add
days to a date.
Remarks
number
A numeric expression specifying the number of
time intervals to add to the date argument.
Positive values add time to the date and
negative values subtract time from the date.
date
A date expression that represents any date or
string value. A specified number of time
intervals can be added to the base date. If a
string literal, enclose in quotation marks.
This function returns a date value. Each part of the date is adjusted
according to the rules of the Gregorian calendar. This includes
adjustments made for leap years and the different number of days in
each month.
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
68
Functions
See Also
DateDiff Function, DatePart Function, Now Function
Example
The following example shows the behavior the DateAdd function when
months are added to a date:
DateAdd("m", 7, "31-Jul-1999")
The function returns a result of 29-Feb-2000. The year 2000 was a leap
year, so the last day of February was the 29th. After the months are
added to the original date, the day value is adjusted backward in time to
ensure the resultant date is valid.
DateConvert Function
Use the DateConvert mask as the source format, not as the target format.
Description
Changes the format of a date string
Return
User-specified format of a supplied date string
Return (Null)
Error: Incorrect argument count.
Syntax
DateConvert("srcfmt", "trgfmt", ("srcstring"))
Parameters
This function has the following parameters:
Name
Description
"srcfmt"
Format of the date string. Enclose
in quotation marks.
"trgfmt"
Format of the date string to return.
Enclose in quotation marks.
("srcstring")
This is a string representing a date
in the format specified by srcfmt.
Enclose in quotation marks.
Year
y
Month
m
Day
d
69
Remarks
If you are using ASCII as both your source and target connector, use this
function. But if you are converting dates from an ASCII file to a SQL
database date field, use the DateValMask Function instead. See
DateValMask Function.
If your source data contains two-digit year values, this function assumes
and appends the workstation’s system century digits when the data is
converted to an application or format where four-digit year values are
used. For information on specifying with an expression exactly which two
century digits you want to have appended, see Using Masks to Convert
Two-digit Dates.
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
See Also
DateValMask Function and DateValue Function
Examples
The following example shows how to convert a 5-digit Julian date where
the year is represented by two digits and the number of days in the year
is represented by three digits. It is converted to an 8-character date string:
DateConvert("yyddd", "mm/dd/yy", FieldAt("/SOURCE/R1/
Field1"))
The following example converts a string date of the format 19981214 to a
date of the format 12/14/1998:
DateConvert("yyyymmdd", "mm/dd/yyyy", FieldAt("/SOURCE/
R1/Field1"))
The following example specifies that all of the dates are between 1900/
01/01 and 1999/12/31. The base century is 1900 and all two-digit years are
mapped into the base century:
DateConvert("mmddYY1900", "yyyymmdd", ("091703"))
The following example indicates that all two-digit years starting with 55
are mapped into the 1900s. The two-digit years that are less than 55 are
mapped into the next century:
DateConvert("mmddYY1955", "yyyymmdd", ("091726"))
The following table lists the set of valid time intervals supported by this function:
70
Time Period
Interval Value
Year
y
Month
m
Day
d
Functions
DateDiff Function
Description
Determine the number of time intervals between two dates
Return
Number of time intervals (i.e., day, week) between two supplied dates
Return (Null)
Error: Incorrect argument count.
Syntax
DateDiff("interval", "date1", "date2")
Parameters
This function has the following parameters:
Remarks
Name
Description
"interval"
A string expression describing the
type of time interval used to
calculate the difference between
the two date arguments. A list of
valid time interval strings is given
below. Enclose in quotation marks.
"date1"
A date expression representing the
first date used in the difference
calculation. Enclose in quotation
marks.
"date2"
A date expression representing the
second date used in the difference
calculation. Enclose in quotation
marks.
To calculate the number of days between date1 and date2, you can use
either Day of year ("y") or Day ("d"). When interval is Weekday ("w"),
DateDiff returns the number of weeks between the two dates. If date1
falls on a Monday, DateDiff counts the number of Mondays until date2. It
counts date2 but not date1. If interval is Week ("ww"), however, DateDiff
returns the number of calendar weeks between the two dates. It counts
the number of Sundays between date1 and date2. DateDiff counts date2
if it falls on a Sunday; but it does not count date1, even if it does fall on a
Sunday.
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
The following table lists the set of valid time intervals supported by this function:
Time period
Interval value
Year
"yyyy"
71
Quarter
"q"
Month
"m"
Day of Year
"y"
Day of the Month
"d"
Day of the Week
"w"
Week
"ww"
Hour
"h"
Minute
"n"
Second
"s"
See Also
DateAdd Function, DatePart Function, Now Function
Example
This example writes the difference in number of days between
the dates in the expression. After running the transformation,
the number 41 is returned to the target field:
DateDiff("d", "02/02/01", "03/15/01")
DatePart Function
Description
Extracts a specified part of a Date string
Return
Part of a date based on a user-specified time interval
Return (Null)
Error: Incorrect argument count.
Syntax
DatePart("interval", "date")
Parameters
The DatePart function uses the following parameters:
72
Name
Description
"interval"
A string expression describing
the type of time interval to
extract from the date
argument. A list of valid time
interval strings is given below.
Functions
"date"
A date expression
representing the whole date
from which the specified part
is to be extracted.
See Also
DateAdd Function, DateDiff Function, Day Function, Hour Function, Minute Function,
Month Function, Now Function, Second Function, Weekday Function, Year Function
Example
The following example writes the day of the year for source dates ("Date") to the target
file:
DatePart ("d", DateValMask(FieldAt("/SOURCE/R1/Date"),"mm/dd/
yyyy"))
Note: The DateValMask function is also used here. The mask, "mm/dd/yyyy", indicates the
format of dates in the source file (not the desired target date format). All source field dates
must be in this format for the function to return the appropriate data to the target. See
DateValMask Function
The following table lists the set of valid time intervals supported by this function.
Time Period
Interval Value
Year
"yyyy"
Quarter
"q"
Month
"m"
Day of year
"y"
Day of month
"d"
Day of the week
"w"
Week
"ww"
Hour
"h"
Minute
"n"
Second
"s"
Remarks
Caution: This function returns a value
that must be used or stored to prevent
stack overflow. See Stack Overflow.
73
DateSerial Function
Description
Constructs a date value
Return
Date value from user-specified year, month, and day values
Return (Null)
Error: Incorrect argument count.
Syntax
DateSerial(year, month, day)
Parameters
This function has the following parameters:
Remarks
Name
Description
year
A number or numeric expression
representing the year part of the
date. Acceptable values for year are
integers between 1 to 25000,
inclusive. Negative year values are
not supported.
month
A number or numeric expression
specifying the month part of the
date. The supported range of
values for month is 1 to 12,
inclusive.
day
An integer value or numeric
expression in the range of 1 to 31.
Some other implementations of DateSerial support the use of argument
values outside of the normal allowable ranges for specifying relative
dates. This implementation only supports absolute dates.
You may also specify a number or numeric expression to determine a
number of days, months and years before or after a date. See Example 2
below.
Values for the year parameter are taken literally. Two digit values cannot
be used to specify years in the current century.
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
See Also
74
DatePart Function, DateValue Function, Day Function, Month Function,
Now Function, Weekday Function, Year Function
Functions
Examples
This example creates a serial date value for January 1, 2003:
DateSerial(2003, 1, 1)
‘This example creates a serial date value for six years, three months and
three days BEFORE the date Dec. 28, 2000. The result returned to the
target is 9/25/1994:
DateSerial(2000-6, 12-3, 28-3)
DateValMask Function
Description
Converts formatted date strings into real date values based on a date edit
mask
Return
Date value from user-specified source date mask and supplied date string
Return (Null)
Error: Incorrect argument count.
Syntax
DateValMask(datestring, srcmask)
Parameters
This function has the following parameters:
Name
Description
datestring
Any valid string expression representing a
formatted date value. It may be entered
as a field name. If a string literal, enclose
in quotation marks.
srcmask
The string expression representing the
source date mask. If a string literal,
enclose in quotation marks.
75
Remarks
If you are converting dates from an ASCII file to a SQL database date field,
use this function. But if you are using ASCII as both your source and target
connector, use the DateConvert Function
If your source data contains two-digit year values, this function assumes
and appends the workstation’s system century digits when the data is
converted to an application or format where four-digit year values are
used. For information on specifying with an expression exactly which two
century digits you want to have appended, see Using Masks to Convert
Two-digit Dates.
If the format of the date in the source does not match the mask, a null is
returned.
No Millisecond Support: Mapping does not support milliseconds; since
thousandths of seconds are not stored, zeros are displayed. When dealing
with milliseconds, check the Size field property to ensure the field is large
enough to avoid a data truncation error.
Caution: This function returns a value that must be used or stored. Failure
to do so causes a stack overflow. See Stack Overflow.
See Also
DateValue Function, DateConvert Function, Managing Dates
Examples
The following example illustrates how to use this function where ("FIELD1")
in the source file contains a date string such as 03231995, and the data in
this field is being converted to a "date" field type in the target application:
DateValMask(FieldAt("/SOURCE/R1/FIELD1"), "mmddyyyy")
The following example concatenates two source fields ("Date Run") and
("Time Run") into a standard date and time format in the target. ("11/22/99
13:52:25"):
DateValMask(Trim(FieldAt("/SOURCE/R1/Date run") ) &
Trim(FieldAt("/SOURCE/R1/Time run") ), "mm/dd/
yyyyHH:MMAm")
This example standardizes data from the source ("DateTime") field. Some
records have a dash between the date and time while others do not. The
mask must be changed for both source formats as follows:
DateValMask(FieldAt("/SOURCE/R1/DateTime"), "yyyy-mm-dd
H24:MM") and
DateValMask(FieldAt("/SOURCE/R1/DateTime"), "yyyy-mm-ddH24:MM")
76
Functions
The following example specifies that all of the dates are between 1900/01/
01 and 1999/12/31. The base century is 1900 and all two-digit years are
mapped into the base century:
DateValMask("091703","mmddYY1900")
The following example indicates that all two-digit years starting with 55 are
mapped into the 1900s. The two-digit years that are less than 55 are
mapped into the next century:
DateValmask("091703","mmddYY1955")
DateValue Function
Description
Convert a character string representation of a date into a date
value
Return
Date value from user-specified date string
Return (Null)
Error: Incorrect argument count.
Syntax
DateValue("datestring")
Parameters
This function has the following parameters:
Remarks
Name
Description
"datestring"
Any valid string expression
representing a formatted date
value. It may be entered as a
field name.
This function is used to convert formatted date strings into real
date values. These date values can then be used in date
calculations or formatted differently.
If your source data contains two-digit year values, this function
assumes and appends the workstation’s system century digits
when the data is converted to an application or format where
four-digit year values are used. For information on how to
specify (in an expression) which two century digits you want to
have appended, see Using Masks to Convert Two-digit Dates.
The date values “00/00/0000” or “00/00/00” are not valid for this
function. These values cause a type mismatch error.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
77
See Also
DateAdd Function,DateDiff Function, DateSerial Function,
DateValMask Function, Day Function, Month Function, Now
Function, Weekday Function, Year Function, Trim, Trim$
Functions, and Val Function
Example
This example converts text date strings in the source field
("Date") to numeric formats. Use the Trim function to remove
leading and trailing spaces in the data so the function works as
expected:
DateValue(Trim(FieldAt("/SOURCE/R1/Date")))
The DateValue function understands dates in the formats shown in the following table. For
each format shown, an example and its associated result is provided.
In these example, the results are calculated assuming the current year is 1994. In other
words, if no year is specified, the resulting year is 1994.
78
Format
Example
Result (yyyymmdd)
mm-dd-yyyy
07-12-1994
19940712
mm-dd-yy
12-03-94
19941203
mm-dd
11-25
19941125
mm/dd/yyyy
01/01/1955
19550101
mm/dd/yy
09/23/47
19470923
mm/dd
08/03
19940803
dd-mon-yyyy
12-Jun-1983
19830612
dd-mon-yy
15-Mar-01
19010315
dd-mon
30-Sep
19940930
dd-month-yyyy
31-October-2315
23151031
dd-month-yy
10-August-58
19580810
dd-month
01-April
19940401
month dd, yyyy
September 26, 1979
19790926
mm.dd.yyyy
09.26.1979
19790926
Functions
Note The results from the DateValue function depend on how your system displays dates. For
example, if you are not getting the expected result on a Windows machine, check the Regional
and Language Options.
Day Function
Description
Extracts the day value
Return
Day of the month from a supplied date value
Return (Null)
Error: Incorrect argument count.
Syntax
Day(date)
Parameters
This function has the following parameters:
Remarks
Name
Description
date
Any value or expression that
can represent a date.
Numeric values are treated as date/time values, where the
fractional part of the number represents time and the whole
part represents a Julian date. Dates formatted as text strings are
interpreted in the same way the DateValue function interprets
date strings.
Null values are treated as a numeric zero.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
DatePart Function, Hour Function, Minute Function, Month
Function, Now Function, Second Function, Weekday Function,
Year Function
Example
This example returns the day of the month for the current date.
(7/13/2000 returns "13" to the target:
Day(Now())
79
This example returns the day of the month for the current
system date and adds 10 (days) to the day of the month value (6/
22/2003 returns "22" to the target):
Day(Now()) + 10
The example below returns the day portion from the source
("ShipDate"). The DateValue function defines each date to be
date values, while the Day function defines those values as days:
a = DateValue(Trim(FieldAt("/SOURCE/R1/
ShipDate") ))Day(a )
DefineMacro Function
Description
Creates a new macro definition
Return
Not applicable for this function
Return (Null)
Error: Too few arguments.
Syntax
DefineMacro(macname, value [, desc[, type]])
Parameters
This function has the following parameters:
Remarks
80
Name
Description
macname
String that defines macro
macname to the value
parameter. If a string literal,
enclose in quotation marks.
value
Stores a value. If a string literal,
enclose in quotation marks.
desc (optional)
String that contains the
description of the macro. If a
string literal, enclose in
quotation marks.
type (optional)
The numeric value is used as
the 'type' of the macro.
Functions
See Also
ClearMacro Function, IsMacroDefined Function, MacroExpand
Function, MacroValue Function
Example
Create a new macro definition called "mymacro":
DefineMacro("mymacro", "100")
DeleteMessage Function
Description
Deletes a message object.
Return
Not applicable for this function.
Return (Null)
Not applicable for this function.
Syntax
DeleteMessage(messageName [, errNotFound] )
Parameters
This function has the following parameters:
Name
Description
messageName
String that contains the name
of the message object to
delete. If a string literal,
enclose in quotation marks.
errNotFound
Boolean setting that
determines whether to
generate a run-time error if
the specified message is not
found.
Remarks
Deletes a message object to reclaim the memory used by the
object.
See Also
DJMessage Object Type, DJComponent Object Type, Using
DJMessage and DJComponent Objects in Expressions
Example
Delete a message object called mymsg:
DeleteMessage("mymsg")
81
Discard Function
Description
Discards a record from a transformation
Return
Not applicable for this function
Return (Null)
No error.
Syntax
Discard(number)
Parameters
This function has the following parameters:
Remarks
Name
Description
n (optional)
Any valid numeric expression.
Use Discard to leave a record out of a transformation. Discarding
is the same as rejecting, except that discarded records are not
written anywhere.
Both the Reject and Discard functions take an optional numeric
argument. If the argument value is zero, the function does
nothing. If the argument is nonzero, then the function discards
the current record.
See Also
Abort Function and Reject Function
Example
The following examples show two ways to discard records where
the value in the ("Account No") field is greater than 10025:
Discard(FieldAt("/SOURCE/R1/Account No") >
10025)
Example 2
If FieldAt("/SOURCE/R1/Account No") > 10025 Then
Discard()
Else
FieldAt("/SOURCE/R1/Account No")
End If
Environ Function
82
Description
Returns the string associated with an operating system
environment variable
Return
Value of the specified environment variable
Return (Null)
Error: Incorrect argument count
Functions
Syntax
Environ({"JAVA_HOME" | number})
Parameters
This function has the following parameters:
Remarks
Name
Description
"envstring" (optional)
String expression containing
the name of an environment
variable.
number (optional)
Numeric expression
corresponding to the numeric
order of the environment
string in the environmentstring table. The number
argument can be any numeric
expression, but is rounded to a
whole number before it is
evaluated.
If envstring cannot be found in the environment-string table, a
zero-length string ("") is returned. Otherwise, Environ returns
the text assigned to the specified envstring; that is, the text
following the equal sign (=) in the environment-string table for
that environment variable.
If you specify number, the string occupying that numeric
position in the environment-string table is returned. In this case,
Environ returns all of the text, including envstring. If there is no
environment string in the specified position, Environ returns a
zero-length string.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
Example
If you specify (1) as the number parameter, the Environ function
returns the string occupying the first position in the
environment string table:
Environ(1)
Eval Function
Description
Evaluates a string expression
Return
Value of a supplied string expression
Return (Null)
Error: Incorrect argument count
83
Syntax
Eval(expression)
Parameters
This function has the following parameters:
Remarks
Name
Description
expression
Any string expression. If a
string literal, enclose in
quotation marks.
Use this function to evaluate a string as if the string were an
actual expression.
This function may return a compile error.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Choose Function, IIf Function, Switch Function
Example
The following example returns 50:
Eval("20 + 30")
Exp Function
Description
Raises e (the base of natural logarithms) to the Nth power
Return
The constant e raised to the Nth power
Return (Null)
Error: Incorrect argument count.
Syntax
Exp(number)
Parameters
This function has the following parameters:
Remarks
Name
Description
number
Any valid numeric expression
greater than zero and less than
709.782712893.
The constant e is approximately 2.718282. This function
complements the action of the Log function and is sometimes
referred to as the antilogarithm.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
84
Functions
See Also
Log Function and Log10 Function
Example
This example returns source ("Field1") as a Double data type,
specifying e (the base of natural logarithms) raised to a power:
Exp(FieldAt("/SOURCE/R1/Field1"))
Extract Function
Description
Extracts a specified character or string
Return
All alpha, all numeric, or alphanumeric strings from a supplied
string
Return (Null)
Error: Incorrect argument count.
Syntax
Extract ("string", "what")
Parameters
This function has the following parameters:
Remarks
Name
Description
"string" (required)
The source string.
"what" (required)
String "a" to extract alpha
characters, "n" to extract
numeric characters (digits), or
"an" to extract alphanumeric.
If the what parameter gives the wrong value, a type mismatch
error occurs (i.e., if an "a" string is written to extract alpha
characters and the source string is numeric, etc.)
Be careful to observe case when using a function that performs
a string-search. String-search Functions are case-sensitive,
literal searches. A Function that searches for "x" disregards "X".
If the function has an optional argument "compare", and you do
not use the optional compare argument, the expression is casesensitive by default.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
The return is a concatenated string.
Example 1
Extract("This is example 437.", "a")
Return 1
Thisisexample
Example 2
Extract("This is example 437.", "n")
85
Return 2
437
Example 3
Extract("This is example 437.", "an")
Return 3
Thisisexample437
FieldAt Function
Description
Translates a field address to a DJField object reference
Return
DJField object
Return (Null)
Syntax
FieldAt(path)
Parameters
This function has the following parameters:
Remarks
Name
Description
path
Path to a DJField object.
You can use any of the DJField variable properties with FieldAt, as follows:
FieldAt("/SOURCE/R1/fieldname”).property
Caution: This function returns a value that must be used or stored to prevent
stack overflow. See Stack Overflow.
See Also
RecordAt Function and DJField Object Type
Example
This example returns the value of Field3:
FieldAt("/SOURCE/R1/Field3”).Value
FileAppend Function
Description
Appends a string to an existing file and creates a new file if it
does not exist
Return
Number of characters written to the file
Return (Null)
Error: Too few arguments.
Syntax
FileAppend("filename", "string", [encoding])
Parameters
This function has the following parameters:
Name
86
Description
Functions
filename (required)
A string containing the name
of the file to append. If a string
literal, enclose in quotation
marks.
string (required)
The string to write to the
overwritten file. If a string
literal, enclose in quotation
marks.
encoding (optional)
The encoding you want to use
on the string to be appended.
For a list of all of the Encoding
Constants available for this
parameter, see the Encoding
Reference.
Remarks
The difference between this function and FileWrite: FileWrite
always overwrites an existing file, while FileAppend creates a
new file, or appends to an existing file.
See Also
FileCopy Function, FileDelete Function, FileList Function,
FileRead Function, FileRename Function, and FileWrite Function
Example
This function creates a new file (if tutor1.asc does not exist) or
append a string to an existing file (if tutor1.asc exists). This
expression appends the string "Add new text" to the end of the
file:
FileAppend("C:\tutor1.asc", "Add new text")
FileCopy Function
Description
Copies the contents of the source file to the target file
Return
Not applicable for this function
Return (Null)
Error: Incorrect argument count.
Syntax
FileCopy(srcfile, trgfile)
Parameters
This function has the following parameters:
Name
Description
87
srcfile (required)
A string containing the name
of the source file. If a string
literal, enclose in quotation
marks. FileCopy(“srcfile”).
trgfile (required)
A string containing the name
of the target file. If a string
literal, enclose in quotation
marks. FileCopy(“trgfile”).
Remarks
A "File not found" exception error occurs if the source file does
not exist. A "File access" exception error also occurs if the file is
in use, if there are permissions to create the file, or if there is
already a file named Trgfile.
See Also
FieldAt Function, FileDelete Function, FileList Function, FileRead
Function, FileRename Function and FileWrite Function
Example
Make a copy of output.xls (an existing file) and name it
output.bak:
FileCopy("C:\output.xls", "C:\output.bak")
FileDateTime Function
Description
File date was last modified or date created
Return
Variant (Date) and time that file was created or last modified
Return (Null)
Error: Incorrect argument count.
Syntax
FileDateTime(pathname)
Parameters
This function has the following parameters:
Remarks
Name
Description
pathname (required)
A string expression that
specifies a file name. If a string
literal, enclose in quotation
marks.
FileDateTime(“pathname”).
Include the directory and drive in the path name string (see
example below).
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
88
Functions
See Also
FieldAt Function, FileCopy Function, FileLen Function,FileList
Function, FileRead Function, FileRename Function, and
FileWrite Function
Example
Insert this line of code:
FileDateTime("C:\testfile.asc")
FileDelete Function
Description
Deletes the specified file
Return
Not applicable for this function
Return (Null)
Error: Incorrect argument count
Syntax
FileDelete(filename)
Parameters
This function has the following parameters:
Name
Description
filename
A string containing the name
of the file to delete. If a string
literal, enclose in quotation
marks. FileDelete(“filename”).
Remarks
A "File not found" exception error occurs if the file does not
exist. A "File access" exception error occurs if the file is in use or
if there are no permissions to delete the file.
See Also
FieldAt Function, FileCopy Function, FileList Function, FileRead
Function, FileRename Function, and FileWrite Function
Example
FileDelete("C:\temp.log")
FileExists Function
Description
Tests for the existence of a file
Return
True (-1) if the specified file name exists
False (0) if the file does not exist
Return (Null)
None.
89
Syntax
FileExists(filename)
Parameters
This function has the following parameters:
Remarks
Name
Description
filename
A string containing the name
of the file to be found. A
complete path specification
(either absolute or relative)
must be provided if the file is
not expected to exist in the
current directory. If a string
literal, enclose in quotation
marks. FileExists(“filename”).
The IsFile and IsDirectory functions check for three possible
conditions (True, False, Error). Use the FileExists function first if
you want to check for a file or directory without the possibility
of returning an error. If it exists, you can then test with IsFile or
IsDirectory.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
FileList Function, FileRead Function, FileRename Function and
FileWrite Function
Example
FileExists("C:\temp.log")
FileLen Function
Description
File length (bytes) as a Long
Return
Long specifying the length of a file in bytes
Return (Null)
Error: Incorrect argument count.
Syntax
FileLen(pathname)
Parameters
This function has the following parameters:
Name
90
Description
Functions
pathname
Remarks
The required pathname
parameter is a string
expression that specifies a file.
The path name may include
the directory and the drive. If a
string literal, enclose in
quotation marks.
FileLen(“pathname”).
If the specified file is open when the FileLen function is called,
the value returned represents the size of the file immediately
before it was opened.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
FileDateTime Function
Example
This expression returns 11455 (11,455 bytes, 11.1kb):
FileLen("C:\Tutor1.asc")
FileList Function
Description
Builds a list of user-specified file types
Return
Number of files in the results list
Return (Null)
Error: Incorrect argument count.
Syntax
FileList(prototype, results)
Parameters
This function has the following parameters:
Name
Description
prototype (required)
A string used as a pattern for
matching file names. The
string can contain literal
characters and the
metacharacters '*' and '?'. If a
string literal, enclose in
quotation marks.
FileList(“prototype”).
results (required)
An array variable for storing
the list of matching file names.
91
Remarks
Returns a 'Type Mismatch' error if the results parameter is not
an array.
The FileList function returns both file and directory names
within a given directory. If you want to work only with file
names, you must test the return names using the IsFile function
to determine which files to use.
Note: The Option Base statement has no effect on the FileList
Function. The FileList Function always sets the array lower
bound to 0.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
IsFile Function, FieldAt Function, FileCopy Function, FileDelete
Function, FileRead Function, FileRename Function and FileWrite
Function
Example
Return a list of all of the script files in the current ' directory:
Dim file_list()
FileList(*.ezscript, file_list)
FileRead Function
92
Description
Specifies the name of the file to read, calls and reads the file
Return
Contents of the specified file
Return (Null)
Error: Too few arguments.
Syntax
FileRead(filename [, encoding [,password]])
Parameters
This function has the following parameters:
Name
Description
filename (required)
Name of file to read. If a string
literal, enclose in quotation
marks. FileRead(“filename”).
Functions
encoding (optional)
The encoding you want to use
on the file to be read.
For a list of the encoding
constants available for this
parameter, see the Encoding
Reference.
password (optional)
Remarks
For password-protected .jar or
.zip file.
The filename parameter must include the entire path name
unless you specify a relative path (the file resides in the current
directory).
You can work with files using the Internet with URI support on
File functions. For details, search for “URI” in the
documentation.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
FieldAt Function, FileCopy Function, FileDelete Function, FileList
Function, FileRename Function, FileWrite Function,
FileReadLine Function
For information on passing encrypted passwords, search for
“writing connection strings” in the documentation.
Example
This expression reads the file tutor1.asc:
FileRead("C:\tutor1.asc")
FileReadLine Function
Description
Reads a user specified line from a file
Return
One user-specified line from a file
Return (Null)
Error: Too few arguments
Syntax
FileReadLine(file, line [, linesep [, encoding]])
Parameters
This function has the following parameters:
Name
Description
93
file (required)
Name of file to read with full path.
If a string literal, enclose in
quotation marks.
FileReadLine(“file”).
line (required)
The line number to read (beginning
with 1 as the first line). See
Remarks.
linesep (optional)
The line separator that identifies
the end of each line in the file.
By default, the line separator (if not
included in the argument list) is CRLF (0x0d 0x0a) on Windows
systems, and LF (0x0a) on Unix
systems.
encoding (optional)
Remarks
The encoding to use on the file to
be read. The encoding default is
ISO8859-1. For a list of all of the
encoding constants available for
this parameter, see the Encoding
Reference.
The file parameter must include the entire path to the file, unless you
specify a relative path (the file resides in the current directory).
The returned line does not include the line separator.
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
Errors
Generates a TYPEMISMATCH error if the line separator is empty or the
encoding is invalid.
Generates a FILEOPEN error if the file cannot be opened.
Generates an EOF error if the end of file is reached before the specified
line is found. (Note that if the line number specified is less than 1, it is
treated as set to 1).
94
Functions
See Also
FieldAt Function, FileCopy Function, FileDelete Function, FileList
Function, FileRename Function, FileWrite Function, FileRead Function
Example
Using a file named "thisfile.txt" as source, with the following content:
"Jones, Mary,1234 First St."
"Smith, Joe, 910 11th Ave."
"New, Mitch, 456 Tequey"
The following expression returns: "New,Mitch,456 Tequey":
FileReadLine("C:\thisfile.txt", 3)
FileRename Function
Description
Changes the name of a file
Return
Not applicable for this function
Return (Null)
Error: Incorrect argument count.
Syntax
FileRename(oldname, newname)
Parameters
This function has the following parameters:
Remarks
Name
Description
oldname
String containing old name of
file. If a string literal, enclose in
quotation marks.
FileRename(“oldname“).
newname
String containing the new
name of the file. If a string
literal, enclose in quotation
marks.
FileRename(“newname”).
A "File not found" exception error occurs if the file does not
exist. A "File access" exception error occurs if the file is in use, if
there are no permissions to rename the file, or if the newname
file already exists.
The file cannot be renamed across different drives (as in from
drive C to drive D), or from one platform to another (from local
PC to server).
95
See Also
FieldAt Function, FileCopy Function, FileDelete Function, FileList
Function, FileRead Function, and FileWrite Function
Example
FileRename("C:\output.xls", "C:\output.bak")
FileWrite Function
Description
Overwrites an existing file. The function’s behavior is similar to
that of the Replace Output mode in the Map window.
Return
Number of characters written
Return (Null)
Error: Incorrect argument count
Syntax
FileWrite (filename, string, [encoding])
Parameters
This function has the following parameters:
Remarks
Name
Description
filename (required)
A string containing the name
of the file to write. If a string
literal, enclose in quotation
marks. FileWrite(“filename”).
string (required)
A string containing the data to
write to the file. If a string
literal, enclose in quotation
marks. FileWrite(“string”).
encoding (optional)
The encoding you want to use
on the value to be written. For
a list of all of the Encoding
Constants available for this
parameter, see the Encoding
Reference.
The difference between FileAppend function and this function is
that FileWrite always overwrites an existing file. FileAppend
creates a new file, or appends to an existing file.
You can work with files using the Internet with URI support on
File functions. For details, search for “URI” in the
documentation.
96
Functions
See Also
FieldAt Function, FileCopy Function, FileDelete Function, FileList
Function, FileRead Function, and FileRename Function
Example
This example writes a date to the file Tutor1:
FileWrite("C:\Tutor1.asc", "07/13/2004")
Filter Function
Description
Searches an array for string match
Return
Zero-based array containing subset of a string array based on a specified
filter criteria
Return (Null)
Error: Invalid expression syntax.
Syntax
Filter(sourcesrray, match[, include[, compare]])
Parameters
This function has the following parameters:
Name
Description
source array (required)
One-dimensional array of strings to
be searched. If a string literal,
enclose in quotation marks.
“match” (required)
Search string.
include (optional)
Boolean value indicating whether
to return substrings that include or
exclude match. If include is True,
Filter returns the subset of the
array that contains match as a
substring. If include is False, Filter
returns the subset of the array that
does not contain match as a
substring.
compare (optional)
Numeric value indicating the kind
of string comparison to use. A value
of 0 performs a binary comparison
(default). A value of 1 performs a
textual comparison.
97
Remarks
If no matches of match are found within sourcearray, Filter returns an
empty array. An error occurs if sourcearray is null or is not a onedimensional array.
The array returned by the Filter function contains only enough elements
to contain the number of matched items.
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
Example
myarray = split("Dish Dist dishes Distribution
Distributor", " ")
resultarray = Filter(myarray, "Dist", 1)
print("result array:'" &
join(resultarray, "' '") "'")
Returns 'Dist' 'Distribution' 'Distributor'
FindMessage Function
Description
Searches for a DJMessage object
Return
Reference to the DJMessage object
Return (Null)
Error: Invalid expression syntax.
Syntax
FindMessage("messagename")
Parameters
This function has the following parameters:
Remarks
Name
Description
"messagename"
The name of the message to find. If
a string literal, enclose in quotation
marks. FindMessage(“string”).
If the message is not found, it returns nothing.
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
98
Functions
See Also
Search for “Uniform Resource Identifier” in the documentation.
Example
You have a process with a map step that puts its output into a DJMessage
object using the URI 'djmessage:///output1'. In this case, you can look up
and use the message in an expression step:
Dim msgout As DJMessage
Set msgout = FindMessage(output1)
If msgout Is Nothing Then
LogMessage("INFO","Can't find the message output1")
Else
LogMessage("INFO","Message output1 has " &
len(msgout.Body) & "
characters")
End If
Fix Function
Description
Find the integer part of a number
Return
Integer portion of a number.
Return (Null)
Error: Invalid expression syntax.
Syntax
Fix(number)
Parameters
This function has the following parameters:
Remarks
Name
Description
number
Any valid numeric expression.
This function removes the fractional part of number and returns
the resulting integer value. If number is negative, Fix returns the
first negative integer greater than or equal to number. The data
type of the return value is the same as that of the number
argument.
The Int function and Fix function behave identically unless
you're working with negative numbers. The Int function rounds
to the lower negative integer while the Fix function rounds to
the higher one.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Abs Function, Int Function, Sgn Function, CInt Function, and
CLng Function
99
Example
The following example converts -98.6 to –98:
Fix(-98.6)
The following example applies the Fix function to each source
field ("Field1"):
Fix(FieldAt("/SOURCE/R1/Field1")
FlushLog Function
Description
Allows you to flush the log to disk anytime you choose
Return
Not applicable for this function
Return (Null)
Not applicable for this function
Syntax
FlushLog()
Parameters
No parameter is required, however, FlushLog must be followed by
open and close parentheses ().
Remarks
If while processing an expression you want to log a warning
message and want to make sure that it was written to disk, you can
flush the log after logging the warning.
This function does not clear messages as in Clear Log File Before
Each Run.
Use FlushLog() in an Execute action to write the log just in case the
transformation fails, or there is a communications error when it
attempts to make the connection to the new source. FlushLog()
enables you to preserve the activity log up to that point.
Example
FlushLog()
Format, Format$ Function
Description
Formats a number, date, time, or string according to instructions contained in a
format expression
Note: The Format and Format$ functions are interchangeable.
Return
Data in user-specified format. See Symbol below.
Return (Null)
Error: Incorrect argument count
100
Functions
Syntax
Format(expression,[fmt])
Parameters
Format[$] returns a String. This function uses these parameters:
Name
Description
expression
Numeric or string expression to be formatted. If a string literal, enclose in
quotation marks. Format(“expression”).
fmt
Format expression, a string of display-format characters that specify how the
expression is to be displayed. Different types of format expressions (numeric,
date/time, or string) can be mixed in a single fmt argument.
If fmt is omitted or is zero-length and expression is a numeric expression,
Format[$] provides the same functionality as the Str[$] function by converting
the numeric value to the appropriate return data type. Note that positive
numbers converted to strings using Format[$] lack the leading space reserved
for displaying the sign of the value, whereas those converted using Str[$] retain
the leading spaces.
You can use any of the symbols in the next table to create a format expression
for numbers.
Remarks
Caution: This function returns a value that must be used or stored to prevent
stack overflow. See Stack Overflow.
See Also
Str, Str$ Functions and GSub Function
Example 1
Formats today's date as a complete date (including day, month, and year)
according to the Short Date setting in the International section of the Windows
Control Panel. If today's date is January 14, 2004, the result is 1/14/04:
Format(Now(), "ddddd")
Example 2
Formats a 10-digit phone number. First, use the GSub Function to take out all
nonalphanumeric characters, such as parentheses and dashes. GSub works well
if you have data entered in different formats. Next, use Format to put the 10
digits into a standard (@@@)- @@@-@@@@ format:
A=GSub("[^A-Za-z0-9n]", "", FieldAt("Field1"))
Format(Trim(A), "(@@@) @@@-@@@@")
101
Symbol
Description
Null String
Displays the number with no formatting.
0
Digit placeholder - Displays a digit or a zero. If there is a digit in the expression being
formatted in the position where the 0 appears in the format string, displays it;
otherwise, displays a zero in that position.
#
Digit placeholder - Displays a digit or nothing. If there is a digit in the expression being
formatted in the position where the # appears in the format string, display it;
otherwise, display nothing in that position.
. (period)
Decimal placeholder - Determines how many digits are displayed to the left and right
of the decimal separator. If the format expression contains only number sign to the left
of this symbol, numbers smaller than 1 begin with a decimal separator. If you want a
leading zero to always be displayed with fractional numbers, use 0 as the first digit
placeholder to the left of the decimal separator instead. The actual character used as a
decimal placeholder in the formatted output depends on the Number Format specified
in the International section of the Microsoft Windows Control Panel. For some
countries, a comma is used as the decimal separator.
%
Percentage placeholder - Expression multiplied by 100. The percent character (%) is
inserted in the position where it appears in the format string.
, (comma)
Thousands separator - Separates thousands from hundreds within a number that has
four or more places to the left of the decimal separator. Standard use if the thousand
separator is specified if the format contains a comma surrounded by digit placeholders
(0 or #). Two adjacent commas or a comma immediately to the left of the decimal
separator means scale the number by dividing it by 1000, rounded as needed. You may
scale large numbers using this technique. For example, you may use the format string
"##0", to represent 100 million as 100. Numbers smaller than 1 million are displayed as
0. The actual character used as the thousand separator in the formatted output
depends on the Number Format specified in the International section of the Control
Panel. For some countries, a period is used as the thousand separator
E- E+ e- e+
Scientific format - If the format expression contains at least one digit placeholder (0 or
#) to the right of E-, E+, e-, or e+, the number is displayed in scientific format and E or
e is inserted between the number and its exponent. The number of digit placeholders
to the right determines the number of digits in the exponent. Use E- or e- to place a
minus sign next to negative exponents. Use E+ or e+ to place a minus sign next to
negative exponents and a plus sign next to positive exponents.
: (colon)
102
Time separator - Separates hours, minutes, and seconds when time values are
formatted. The actual character used as the time separator depends on the Time
Format specified in the International section of the Control Panel.
Functions
Symbol
Description
/
Date Separator - Separates the day, month, and year when date values are formatted.
The actual character used as the date separator in the formatted output depends upon
the Date Format specified in the Windows Control Panel in Regional and Language
Options.
+ $ ( ) space
Displays a literal character. To display a character other than one of those listed,
precede it with a backslash ( \ ) or enclose it in double quotation marks (" ").
\
Displays the next character in the format string, Many characters in the format
expression have a special meaning and cannot be displayed as literal characters unless
they are preceded by a backslash. The backslash itself is not displayed. Using a
backslash is the same as enclosing the next character in double quotation marks. To
display a backslash, use two backslashes ( \\ ). Examples of characters that cannot be
displayed as literal characters are the date- and time-formatting characters (a, c, d, h,
m, n, p, q, s, t, w, y, /, and :), the numeric-formatting characters (#, 0, %, E, e, comma,
and period),
"ABC"
Displays the string inside the quotation marks
*
Displays the next character as the fill character. Any empty space in a field is filled with
the character following the asterisk.
This table outlines how the formats are applied and contains several examples.
If You Use...
The result is ...
One Section Only
The format applies to all values.
Two Sections
The first section applies to positive values and zeros, the second
section applies to negative values.
Three Sections
The first section applies to positive values, the second section
applies to negative values, and the third section applies to zeros.
Four Sections
The first section applies to positive values, the second section
applies to negative values, the third section applies to zeros, and
the fourth section applies to null values.
Note: Unless the fmt argument contains one of the named formats, a format expression for numbers can
have one to four sections separated by semicolons.
103
Format (fmt)
Pos 5
Neg 5
Dec. 5
Note: Some format examples for numbers are shown below. These examples assume the International
Country code is set for the United States. The first column contains specific format strings. The other
columns contain the output that results if the formatted data has the value given in the column heading.
Null string
5
-5
0.5
0
5
-5
1
0.00
5.00
-5.00
0.50
#,##0
5
-5
1
#,##0.00;;;Nil
5.00
-5.00
0.50
$#,##0;($#,##0)
$5
($5)
$1
$#,##0.00;($#,##0.00)
$5.00
($5.00)
$0.50
0%
500%
-500%
50%
0.00%
500.00%
-500.00%
50.00%
0.00E+00
5.00E+00
-5.00E+00
5.00E-01
0.00E-00
5.00E00
-5.00E00
5.00E-01
Symbol
Description
Note: You may format date and time serial numbers using date and time or number formats (because date/
time serial numbers are stored as floating-point values.) You may use any of the following symbols to create
a format expression for dates and times:
c
Displays the date as ddddd and display the time as t t t t t, in that order. Only date
information is displayed if there is no fractional part to the date serial number; only
time information is displayed if there is no integer portion.
d
Displays the day as a number without a leading zero (1 - 31).
dd
Displays the day as a number with a leading zero (01 - 31).
ddd
Displays the day as an abbreviation (Sun - Sat).
dddd
Displays the day as a full name (Sunday - Saturday).
ddddd
Displays a date serial number as a complete date (including day, month, and year)
formatted according to the Short Date setting in the International section of the
Windows Control Panel. The default Short Date format is m/d/yy.
104
Functions
Symbol
Description
dddddd
Displays a date serial number as a complete date (including day, month, and year)
formatted according to the Long Date setting in the International section of the
Windows Control Panel. The default Long Date format is mmmm dd, yyyy.
w
Displays the day of the week as a number (1 for Sunday through 7 for Saturday).
ww
Displays the week of the year as a number (1 - 53).
m
Displays the month as a number without a leading zero (1-12). If m immediately
follows h or hh, the minute rather than the month is displayed.
mm
Displays the month as a number with a leading zero (01-12). If m immediately follows
h or hh, the minute rather than the month is displayed.
mmm
Displays the month as an abbreviation (Jan - Dec).
mmmm
Displays the month as a full month name (January - December).
q
Displays the quarter of the year as a number (1-4).
y
Displays the day of the year as a number (1-366).
yy
Displays the year as a two-digit number (00-99).
yyyy
Displays the year as a four-digit number (100-9999).
h
Displays the hour as a number without leading zeros (0 - 23).
hh
Displays the hour as a number with leading zeros (00 - 23).
n
Displays the minute as a number without leading zeros (0 - 59).
nn
Displays the minute as a number with leading zeros (00 - 59).
s
Displays the seconds as a number without leading zeros (0 - 59).
ss
Displays the seconds as a number with leading zeros (00 - 59).
ttttt
Displays a time serial number as a complete time (including hour, minute, and
seconds) formatted using the time separator defined by the Time Format in the
International section of the Windows Control Panel. A leading zero is displayed if the
Leading Zero option is selected and the time is before 10:00 A.M. or P.M. The default
time format is h:nn:ss.
AM/PM
Uses the 12-hour clock and displays an uppercase AM for any hour before noon;
displays an uppercase PM for any hour between noon and 11:59 PM.
105
Symbol
Description
am/pm
Uses the 12-hour clock and displays a lowercase AM for any hour before noon;
displays a lowercase PM for any hour between noon and 11:59 PM.
A/P
Uses the 12-hour clock and displays an uppercase A for any hour before noon;
displays an uppercase P for any hour between noon and 11:59 PM.
a/p
Uses the 12-hour clock and displays a lowercase A for any hour before noon; displays
a lowercase P for any hour between noon and 11:59 PM.
AMPM
Uses the 12-hour clock and displays the contents of the 1159 string (s1159) in the
WIN.INI file for any hour before noon; displays the contents of the 2359 (s2359) for
any hour between noon and 11:59 PM. AMPM can be either uppercase or
lowercase, but the case of the string displayed matches the string as it exists in the
WIN.INI file. The default format is AM/PM.
Symbol
Meaning
Note: Use any of the following symbols to create a format expression for strings.
@
Character placeholder - Displays a character or a space. If there is a character in the string
being formatted in the position where the @ appears in the format string, display it;
otherwise, display a space in that position. Placeholders are filled from right to left unless
there is an ! character in the format string. See below.
&
Character placeholder - Displays a character in the string being formatted in the position
where the & appears, display it; otherwise, display nothing. Placeholders are filled from
right to left unless there is an ! character in the format string. See below.
<
Force lowercase – All characters are displayed in lowercase format.
>
Force uppercase – All characters are displayed in uppercase format.
!
Force placeholders to fill from left to right, instead of from right to left.
GetDirectory Function
106
Description
Finds the name of the current directory
Return
Name of the current directory or folder
Return (Null)
Not applicable for this function
Syntax
GetDirectory()
Parameters
No parameters are required, however, GetDirectory must be
followed by parentheses.
Functions
Remarks
This function returns the full path name of the current working
directory of the application process.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
MakeDirectory Function and RemoveDirectory Function
Example
FileWrite("The current directory is " &
GetDirectory())
GetObject Function
Description
Locate an ActiveX object reference
Return
Returns a reference to an object provided by an ActiveX
component
Return (Null)
Error: Invalid expression syntax
Syntax
GetObject("objectname", [classname])
Parameters
This function has the following parameters:
Remarks
Name
Description
"objectname" (required)
Full path name of the file
containing the object to
retrieve. Enclose in quotation
marks.
classname (optional)
A string representing the
object class name.
Use GetObject to access an ActiveX object from a file and assign
the object to an object variable. Use the Set statement to assign
the object returned by the GetObject to the object variable.
Note: Use GetObject when there is a current instance of the
object, or if you want to create the object with a file already
loaded. If there is no current instance, and you do not want the
object started with a file loaded, use CreateObject.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
107
See Also
CreateObject Function
Example
Dim xlApp As Object
Set xlApp = GetObject("Excel.Application")
GetThreadID Function
Description
Identifies the individual thread running a specific process
Return
Unique string that represents the thread ID
Return (Null)
Not applicable for this function
Syntax
GetThreadID()
Parameters
None.
Remarks
When you run a process using multiple threads, it is sometimes critical
to know, within the transformation, which particular thread that
transformation is using. This enables you to create and use global objects
such as message objects and import objects.
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
See Also
MakeDirectory Function and RemoveDirectory Function
Example
‘Returns 000003c4:
GetThreadID()
GSub Function
Description
Globally replaces every instance of an expression string in one
field of data with a specified string. You may substitute
ReplaceAll for GSub, as both are identical in syntax.
Return
Value specified in "newstring" (overwrites "oldstring")
Return (Null)
Error: Incorrect argument for function.
Syntax
GSub(oldstring, newstring, ("string"))
Parameters
This function has the following parameters:
Name
108
Description
Functions
Remarks
oldstring
The original string that the
expression searches for to
replace with the newstring. If a
string literal, enclose in
quotation marks.
GSub(“oldstring”).
newstring
The string that replaces every
instance of the oldstring. If a
string literal, enclose in
quotation marks.
GSub(“newstring”).
fieldname
Any string containing data. If a
string literal, enclose in
quotation marks.
The return value of this function is the string specified by the
fieldname parameter. All sections that match the regular
expression specified as the oldstring parameter are replaced by
the string specified as the newstring parameter.
Be careful to observe case when using a function that performs
a string-search. String-search functions are case-sensitive.
GSub recognizes all special characters in the oldstring
parameter. See Regular Expressions.
If you attempt to use this function on very large strings (50K –
100K and above), you may experience a performance hit. To
avoid long runtimes of your transformations, do not use GSub
on very large strings.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
InitCaps Function, LCase, LCase$ Functions, LTrim, LTrim$
Functions, StrReplace Function, Sub Function, Transliterate
Function, UCase, UCase$ Functions
109
Example 1
Escaping of special characters – You may not think that the
parentheses are special characters. However, to replace
parentheses with this function, parentheses (and all special
characters) must be escaped to be recognized.
The '(' and ')' characters are used for grouping in regular
expressions. The expression "(abc)" matches one or more
occurrences of the string abc. If you want to search for the literal
characters "("and ")", use a backslash as an escape character.
Below, the special characters "(" and ")" in Field1 are escaped
with the "\" symbol, and replaced by an empty string in the
target:
GSub("\(", " ", GSub("\)", " ", FieldAt("/SOURCE/
R1/Field1")))
Example 2
Replace "Avenue" with "Ave." in the Address field:
GSub("Avenue", "Ave.", FieldAt("Address"))
Example 3
Look for "Mon" or "Fri" in ("Field1") of the source file and
replace them with "Monday" and "Friday", respectively. If any
value is found in ("Field1") other than "Mon" or "Fri", leave data
alone:
T = GSub("Mon.", "Monday", FieldAt("/SOURCE/R1/
Field1"))
GSub("Fri.", "Friday", T)
Example 4
Another way to do the previous example is to nest the two
substitutions together:
GSub("Mon.", "Monday", GSub("Fri.", "Friday",
FieldAt("/SOURCE/R1/FIELD1")))
Example 5
If you want to delete blank spaces within a character field, you
must put two spaces before the asterisk in the first parameter
and no space between the quotes in the second parameter.
("FIELD") is the field name of the character field in your source
file from which you want to delete the blank spaces:
GSub(" *", "", FieldAt("/SOURCE/R1/FIELD"))
Example 6
To delete all non alphanumeric characters from a field:
GSub("[^A-Za-z0-9n]","", FieldAt("/SOURCE/R1/
Field1"))
110
Functions
Hex Function
Description
Prints the hexadecimal representation of a number
Return
String representing the hexadecimal value of a supplied number
Return (Null)
Error: Incorrect argument for function.
Syntax
Hex (number)
Parameters
This function has the following parameters:
Remarks
Name
Description
number (required)
Any numeric expression. See
Remarks.
If number is
Hex returns
Null
Null
Empty
Zero (0)
Any other number
Up to eight octal characters
You can represent hexadecimal numbers directly by preceding
numbers in the proper range with &H. For example, &H10
represents decimal 16 in hexadecimal notation.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Oct Function
Examples
Dim MyHex
MyHex = Hex(5) 'Returns 5.
MyHex = Hex(10) 'Returns A.
Hour Function
Description
Converts clock time to an hour integer
Return
Integer between 0 and 23, inclusive, which represents the hour
of the day corresponding to the time provided as an argument.
Return (Null)
Error: Incorrect argument count for function.
Syntax
Hour(number)
111
Parameters
This function has the following parameters:
Remarks
Name
Description
number
Any numeric expression that
can represent a date or time
from January 1, 100 through
December 31, 9999, where
January 1, 1900 is 2.
Numbers to the left of the decimal point in number represent
the date; numbers to the right of the decimal point represent
the time. Negative numbers represent dates prior to December
30, 1899.
If number is null, this function returns a null.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
DatePart Function, Day Function, Minute Function, Month
Function,Now Function, Second Function, Weekday Function,
Year Function
Example
Return the hour portion of the system time to the target field (if
system time is 1:12:30, this function returns "1" to the target:
Hour(FieldAt("/SOURCE/R1/Field1"))
Return the hour portion from the source ("Hour"). The
TimeValue function defines each time to be time values, while
the Hour function defines those values as hours:
a = TimeValue(Trim(FieldAt("/SOURCE/R1/Hour")))
Hour(a)
IIf Function
Description
Returns a value based on whether an expression evaluates to true or false
Return
One of two arguments depending on the evaluation of an expression
Return (Null)
Error: Incorrect argument count for functio
Syntax
IIf(expr, "truepart", "falsepart")
Parameters
This function has the following parameters:
Name
112
Description
Functions
Remarks
expr
Expression you want to evaluate.
"truepart"
Value or expression returned if expr is
True(-1).
"falsepart"
Value or expression returned if expr is
False(0).
You may use IIf (immediately if) to evaluate an expression and return either of
two other values.
Caution: This function returns a value that must be used or stored to prevent
stack overflow. See Stack Overflow.
See Also
Choose Function
Example
In this example, if ("Account No") is greater than 10025 then insert "Bill", else
insert an empty string "":
IIf(Val(FieldAt("/SOURCE/R1/Account No")) > 10025 and
Val(FieldAt("/SOURCE/R1/Account No")) < 10090, "Bill", "")
InitCaps Function
Description
Converts the first character of each word to uppercase. If the
word resembles a name, a recognized abbreviation, or contains
a hyphen, InitCaps applies additional capitalization. See
Remarks for further information.
Return
Returns the modified string.
Return (Null)
Error: Incorrect argument count for function.
Syntax
InitCaps(“string”)
Parameters
This function has the following parameters:
Name
Description
string
Any valid string expression.
Also can be entered as a field
name. If a string literal,
enclose in quotation marks.
InitCaps(“string”).
113
Remarks
Data in the string may be all lowercase, all uppercase, or any
combination of the two.
InitCaps applies additional capitalization under specialized
conditions, as follows:
Certain titles and abbreviations are always capitalized this way:
RR, PO, PhD, MD
If the string starts with "mc" and the third letter is a consonant,
it is converted to McX.
Example: McKone
If the string starts with "mac", "van" or "von" and the fourth
character is a consonant, it is converted to MacX, VanX or VonX.
The only exception to this behavior is Vancouver.
Example: VanDyke
If the string starts with a word followed by a hyphen, the second
word is capitalized.
Example: Martin-Lewis
If the string starts with a capital letter followed by an
apostrophe, the second letter is capitalized.
Example: O’Toole
Note: Because of these special cases, certain words treated as
names may be capitalized inappropriately. For example,
"machine" and "vantage" become "MacHine" and "VanTage."
See Also
LCase, LCase$ Functions, UCase, UCase$ Functions
Example
The following expression would be used to convert the first
character of the names in a field in the source called ("NAME")
to uppercase (with the remainder in lowercase) in the target file:
InitCaps(FieldAt("/SOURCE/R1/NAME")
InStr Function
114
Description
Find the position of the first occurrence of one string within
another string. You may use Search instead of InStr, as both have
the same syntax.
Return
Position of the first occurrence of one string within another
string
Functions
Return (Null)
Error: Too few arguments for function.
Syntax 1
InStr([start,] "strexpr1", "strexpr2")
Syntax 2
InStr(start, "strexpr1", "strexpr2", compare)
Parameters
This function has the following parameters:
Name
Description
start
Numeric expression that sets
the starting position for each
search; start must be between
1 and approximately 65,500. If
start is omitted, the search of
strexpr1 begins at the first
character position. The start
argument is not optional if the
compare argument is
specified.
strexpr1
String expression being
searched. If a string literal,
enclose in quotation marks.
strexpr2
String expression being
sought. If a string literal,
enclose in quotation marks.
compare
Specifies the stringcomparison method. The
argument compare must be 0
or 1. If compare is 0, string
comparison is case-sensitive. If
compare is 1, string
comparison is not casesensitive.
115
Remarks
If strexpr2 is found within strexpr1, InStr returns the position at
which the match was found. If strexpr2 is zero-length, start is
returned. If start is greater than strexpr1, strexpr1 is zero-length,
or strexpr2 can't be found, InStr returns 0.
If either string expression is null, the function returns a null. If
start or compare is null, an error occurs.
Be careful to observe case when using a function that performs
a string-search. String-search Functions are case-sensitive,
literal searches. A Function that searches for "x" disregards "X".
If the function has an optional argument "compare", and you do
not use the optional compare argument, the expression is casesensitive by default.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
InStrRev Function
Example
This example illustrates how you can find the position of a dollar
sign ($) within a source field ("Field1"). It begins the search in
the first byte of data in ("Field1") and the search is not case
sensitive:
Instr(1, FieldAt("/SOURCE/R1/Field1"), "$", 1)
Applied to a field with sale price $14.00
Returns: 12
InStrRev Function
Description
Find the position of an occurrence of one string within another,
from the end of string
Return
Position of the first occurrence of one string within another
string
Return (Null)
Error: Too few arguments for function
Syntax
InstrRev(stringcheck, stringmatch[, start[, compare]])
Parameters
This function has the following parameters:
Name
116
Description
Functions
Return Values
stringcheck (required)
String expression being
searched. If a string literal,
enclose in quotation marks.
InstrRev(“stringcheck”).
stringmatch (required)
String expression being
searched for. If a string literal,
enclose in quotation marks.
InstrRev(“stringmatch”).
start (optional)
Numeric expression that sets
the starting position for each
search. If omitted, –1 is used,
which means that the search
begins at the last character
position. If start contains null,
an error occurs.
compare (optional)
Numeric value indicating the
kind of comparison to use
when evaluating substrings. If
omitted, a binary comparison
is performed. A value of 0
performs a binary comparison
(default), while a value of 1
performs a text comparison.
If . . .
InStrRev Returns . . .
stringcheck is zero-length
0
stringcheck is null
Null
stringmatch is zero-length
start
stringmatch is Null
Null
stringmatch is not found
0
stringmatch is found within
stringcheck
Position at which match is
found.
start > Len(stringmatch)
0
117
Remarks
This function resembles the InStr function, but it starts at the
end of the string and moves backward.
Remember case when using a function that performs a stringsearch. String-search functions are case-sensitive, literal
searches. A function that searches for "x" disregards "X". If the
function has an optional argument "compare", and you do not
use the optional compare argument, the expression is casesensitive by default.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
InStr Function
Example
This example illustrates how you can find the position of a dollar
sign ($) within a source field ("Field1"). It begins the search in
the last byte of data (-1) in ("Field1"). The search is not casesensitive:
InStrRev(FieldAt("/SOURCE/R1/Field1"), "$", -1)
Applied to a field with sale price $14.00
Returns: 12
Int Function
118
Description
Extract the integer of a number
Return
Integer portion of a number
Return (Null)
Error: Incorrect argument count for function.
Syntax
Int(number)
Parameters
This function has the following parameters:
Name
Description
number
Any valid numeric expression.
Functions
Remarks
Int removes the fractional part of number and returns the
resulting integer value.
The data type of the return value is the same as that of the
number parameter. If the numeric expression results in a null, Int
returns a null.
If number is negative, Int returns the first negative integer less
than or equal to number.
The Int and Fix functions behave identically unless you are
working with negative numbers. The Int function rounds to the
lower negative integer, while the Fix function rounds to the
higher one.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Abs Function, Fix Function, Sgn Function, CInt Function, and
CLng Function
Example
The following example returns -99:
Int(-98.6)
IsArray Function
Description
Test a variable to determine if it is an array
Return
Boolean value indicating whether a variable is an array
Return (Null)
Error: Incorrect argument count for function.
Syntax
IsArray(identifier)
Parameters
This function has the following parameters:
Name
Description
identifier
The required identifier
argument specifies a variable.
119
Remarks
IsArray returns True (-1) if the variable is an array; otherwise, it
returns False (0).
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
Example
The following expression returns –1 if VarX is an array, and
returns 0 if VarX is not an array:
IsArray(VarX)
IsDate Function
Description
Test a value to determine if it can be converted into a date type
Return
Value indicating whether or not another value can be converted to a date
Return (Null)
Error: Incorrect argument count for function.
Syntax
IsDate(value)
Parameters
This function has the following parameters:
Remarks
Name
Description
value
Expression to be tested. If a string
literal, enclose in quotation marks,
IsDate("value").
Returns True (-1) if the expression is a valid date or can be converted one;
otherwise, it returns False (0). The range of valid dates is January 1, 1 A.D.
through December 31, 9999 A.D.
IsDate checks for date formats yyyy-m-d and yyyy/m/d. If neither matches, it
tries converting the value to a number; if that succeeds, it tries assigning it as a
date and checking for a year between 1 and 9999. If no match, it returns False.
To evaluate to True:
• There must be a field separator
• The expression must include a year (when converted to a date) between 1 and
9999, inclusive.
Caution: This function returns a value that must be used or stored to prevent
stack overflow. See Stack Overflow.
120
Functions
Formats
This list shows expressions for January 1, 2003 that evaluate to True (-1) or False
(0).
Evaluates to TRUE
IsDate("2003/01/01")
IsDate("01/01/2003")
IsDate("2003-01-01")
IsDate("03-01-01")
IsDate("01-01-2003")
IsDate("01-01-03")
IsDate("2003-1-1")
IsDate("January 01, 2003")
IsDate("01-Jan-03")
IsDate("2003.01.01")
IsDate("01.01.2003")
Evaluates to FALSE
IsDate("010103")
IsDate("January 01 2003")
IsDate("Jan 01 2003")
IsDate("Jan-01-2003")
IsDate("20030101")
IsDate("030101")
See Also
IsNull Function and IsNumeric Function
Example
Examine Field1 in the source file. If Field1 contains a valid date, then write "This
is a valid date." to the target. If Field1 does not contain a valid date, then write
"This is an invalid date." to the target.
IIf(IsDate(FieldAt("/SOURCE/R1/Field1"))= -1, "This is a
valid date.", "This is an invalid date.")
121
IsDirectory Function
Description
Determines whether a filename is a directory or not.
Return
True (if it is a directory), false (if it is a file), or an error if the
filename parameter does not exist (is not a file or directory).
Return (Null)
Error: Incorrect argument count for function.
Syntax
IsDirectory(directoryname)
Parameters
This function has the following parameters:
Name
Description
directoryname
A string containing the name
of the directory to be found. A
complete path specification
(either absolute or relative)
must be provided if the
directory is not expected to
exist in the current working
directory. If a string literal,
enclose in quotation marks.
IsDirectory(“directoryname”).
The IsFile and IsDirectory functions check for three possible
conditions (True, False, Error). Use the FileExists function first if
you want to check for a file or directory without the possibility
of returning an error. If it exists, you can then test with IsFile or
IsDirectory.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
FileList Function, FileRead Function, and IsFile Function
Example
To test for the existence of a directory, use the following syntax:
If FileExists("C:\temp") Then
If IsDirectory("C:\temp") Then
LogMessage("INFO","Is a Directory"))
End If
Else
LogMessage("INFO","Not a Directory")
End If
122
Functions
IsFile Function
This function works only with files. You cannot name a database file and specify a table.
You cannot use this function with SQL-based connectors such as Oracle and SQL Server.
Description
Determines whether a filename is a file or not.
Return
True (if it is a directory), false (if it is a file), or an error if the
filename parameter does not exist (is not a file or directory).
Return (Null)
Error: Incorrect argument count for function
Syntax
IsFile(filename)
Parameters
This function has the following parameters:
Name
Description
filename
A string containing the name
of the file whose existence is
to be determined. A complete
path specification (either
absolute or relative) must be
provided if the file is not
expected to exist in the current
directory. If a string literal,
enclose in quotation marks.
IsFile(“filename”).
The IsFile and IsDirectory functions check for three possible
conditions (True, False, Error). Use the FileExists function first if
you want to check for a file or directory without the possibility
of returning an error. If it exists, you can then test with IsFile or
IsDirectory.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
FileExists Function, FileList Function, FileRead Function,
IsDirectory Function
Example
IsFile("C:\test.dbf")
123
IsMacroDefined Function
Description
Test and see if a macro is defined or not
Return
Boolean value indicating whether or not a macro is defined
True returns a value of -1, while False returns a value of 0.
Return (Null)
Error: Incorrect argument count for function.
Syntax
IsMacroDefined(macname)
Parameters
This function has the following parameters:
Name
Description
macname
Name of the macro to
determine whether it is
defined or undefined. If a
string literal, enclose in
quotation marks.
IsMacroDefined(“macname”)
Remarks
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
DefineMacro Function, MacroValue Function,MacroExpand
Function, ClearMacro Function
Example
Undefines a previously defined macro called "mymacro":
IsMacroDefined("mymacro")
IsNull Function
Description
Test a value for a special null value
Return
Value that indicates whether or not another value contains the special null
value. True returns a value of -1, while False returns a value of 0.
Return (Null)
True
Syntax
IsNull(value)
Parameters
This function has the following parameters:
Name
Description
124
Functions
value
Any expression. If a string literal, enclose in quotation marks. IsNull(“value”)
Remarks
The IsNull function returns True if the expression contains the null value;
otherwise, it returns False.
The null value indicates that the value contains no data. Null is not the same
as Empty, which indicates that a value has not yet been initialized. It is also
not the same as a zero-length string, which is often referred to as a null
string.
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
See Also
IsDate Function and IsNumeric Function
Example 1
The following expression examines source ("Field1") and determines
whether or not it is null:
IsNull(FieldAt("/SOURCE/R1/Field1"))
Example 2
The following example builds upon the example above by using additional
functions. It uses the IsNull function to determine whether the value of a
field is null and employs an If Then Else statement and FileWrite and
InputBox functions. If the field is null, a message prompts the user to enter
data. If the field is not null, the contents of source ("Field1") are returned to
the target:
If IsNull(FieldAt("/SOURCE/R1/Field1")) Then
InputBox ("Please enter data here.")
Else
FieldAt("/SOURCE/R1/Field1")
End If
IsNumeric Function
Description
Test a value variable and determine if it can be converted to a
numeric data type
Return
Boolean value indicating whether or not a value variable can be
converted to a numeric data type. True returns a value of –1,
while False returns a value of 0.
Return (Null)
Error: Incorrect argument count for function.
Syntax
IsNumeric("value")
Parameters
This function has the following parameters:
125
Remarks
Name
Description
value
Any expression. If a string
literal, enclose in quotation
marks.
This function returns True (-1) if value can legally be converted
to a number; otherwise, it returns False (0).
Some operating systems (including Windows) recognize the
letters 'd' and 'D' as valid exponent notations. For example, the
string "1d4" can be converted to a valid number (1x10^4, or
10,000).
A valid number is composed of:
• an optional sign (+ or -)
• one or more decimal digits
• an optional exponent consisting of: the letter 'd', 'D', 'e', 'E'.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
IsDate Function and IsNull Function
Example
The following expression examines the data in the source
("Account No") field and determines whether or not it can be
converted to a numeric data type:
IsNumeric(FieldAt("/SOURCE/R1/Account No"))
IsObject Function
126
Description
Test if an identifier represents an object variable
Return
Boolean value indicating whether an identifier represents an
object variable. True returns a value of –1, while False returns a
value of 0.
Return (Null)
Error: Incorrect argument count for function
Syntax
IsObject(identifier)
Parameters
This function has the following parameters:
Name
Description
identifier
The required identifier
argument is a variable name.
Functions
Remarks
IsObject is useful only in determining whether a Variant is of
VarType vbObject. This could occur if the Variant actually
references (or once referenced) an object, or if it contains
Nothing.
IsObject returns True if identifier is a variable declared with
object type or any valid class type or a user-defined object;
otherwise, it returns False. IsObject returns True even if the
variable has been set to Nothing.
Use error trapping to be sure that an object reference is valid.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
Example
The following expression returns –1 if VarX is an object, and
returns 0 if VarX is not an object:
IsObject(VarX)
Join Function
Description
Concatenates the elements of an array together into a single
string
Return
String consisting of all of the elements of an array
Return (Null)
Error: Too few arguments for function
Syntax
Join(sourcearray[, delimiter])
Parameters
This function has the following parameters:
Name
Description
source array (required)
One-dimensional array
containing substrings to be
joined.
delimiter (optional)
String character used to
separate the substrings in the
returned string. If a string
literal, enclose in quotation
marks. Join(“delimiter”).
127
Remarks
If delimiter is omitted, the space character (" ") is used. If
delimiter is a zero-length string (""), all items in the list are
concatenated with no delimiters.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Split Function
Example
In the following examples, MyArray holds the names "John
Smith", "Joe Jones", and "Dave Davis":
Join(MyArray)
Returns
John Smith Joe Jones Dave Davis
In the second example, commas are added to separate the
names:
Join(MyArray, ",")
Returns
John Smith, Joe Jones, Dave Davis
LBound Function
128
Description
Find the index of the first element (lower bound) in an array or
an array dimension
Return
Lower bound of an array
Return (Null)
Error: Invalid expression syntax.
Syntax
LBound(ArrayName[, Dimension])
Parameters
This function has the following parameters:
Name
Description
arrayname (required)
The array variable name.
dimension (optional)
Is a whole number indicating
which dimension's lower
bound is returned. Use 1 for
the first dimension, 2 for the
second, and 3 for the third. If
dimension is omitted, 1 is
assumed.
Functions
Remarks
Each element of an array stores one value and is referenced by
using its index (coordinate position) after the array name. The
index of the first element of an array is called its lower bound.
The index of the last element is called its upper bound. (See
“UBound Function.” ) By default, an array is indexed beginning
with zero. The upper and lower bounds of an array can be
inspected using LBound and UBound.
Scalar and Undeclared Variables: Using scalar variables and/or
undeclared variables results in a runtime error. Always declare
all variables before using LBound.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
Example
Dim MyArray(1 To 100, 0 To 10, -5 To 5)
LBound(MyArray) (returns 1)
LBound(MyArray, 1) (returns 1)
LBound(MyArray, 2) (returns 0)
LBound(MyArray, 3) (returns -5)
LCase, LCase$ Functions
Description
Converts a string argument to lowercase
Note: The LCase and LCase$ functions are interchangeable.
Return
String in which all letters of an argument have been converted
to lowercase
Return (Null)
Error: Incorrect argument count
Syntax
LCase[$](strexpr)
Parameters
This function has the following parameters:
Remarks
Name
Description
strexpr
Any string expression or
source field. If a string literal,
enclose in quotation marks.
LCase(“strexpr”)
LCase[$] returns a string
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
129
See Also
InitCaps Function and UCase, UCase$ Functions
Example
This expression causes data in source ("Field1") the to be
returned to the target as all lowercase:
LCase$(FieldAt("/SOURCE/R1/Field1"))
This example "cleans the source ("Field1") by making a standard
case requirement in specific parts of addresses, such as "St" and
"Ste". Any periods used in abbreviation are removed when data
is returned to the target. Note the use of the Add1Part and
InitCaps functions in the expression:
Add1Part("NU", FieldAt("/SOURCE/R1/Field1"))&"
"& Add1Part("PRD", FieldAt("/SOURCE/R1/Field1"))
&" "& InitCaps(LCase(Add1Part("SN", FieldAt("/
SOURCE/R1/Field1")))) & " "&
InitCaps(LCase(Add1Part("SU", FieldAt("/SOURCE/
R1/Field1")))) &" "& Add1Part("POD", FieldAt("/
SOURCE/R1/Field1")) &" "&
InitCaps(LCase(Add1Part("SAU", FieldAt("/SOURCE/
R1/Field1")))) &" "& Add1Part("SAR", FieldAt("/
SOURCE/R1/Field1")) &" "& Add1Part("REM",
FieldAt("/SOURCE/R1/Field1"))
Left, Left$ Functions
Description
Returns the left part of a string.
Note: The Left and Left$ functions are interchangeable.
130
Return
Leftmost n characters of a string argument
Return (Null)
Error: Incorrect argument count
Syntax
Left[$](strexpr,n)
Parameters
This function has the following parameters:
Name
Description
strexpr
Any string expression. If a
string literal, enclose in
quotation marks.
Left("strexpr”)
Functions
n
Remarks
A Long expression indicating
how many characters to
return. It must be between 0
and approximately 65,500,
inclusive. If n is 0, the return
value is a zero-length string. If
n is greater than or equal to
the number of characters in
strexpr, the entire string is
returned.
Left[$] returns a String.
The argument strexpr can be any string expression.
The argument n is a Long expression indicating how many
characters to return. It must be between 0 and approximately
65,500, inclusive. If n is 0, the return value is a zero-length string.
If n is greater than or equal to the number of characters in
strexpr, the entire string is returned.
To find the number of characters in strexpr, use Len(strexpr).
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Len Function, Mid, Mid$ Functions, and Right, Right$ Functions
Example
This example returns the three leftmost characters of the source
field named ("Field1"):
Left$(FieldAt("/SOURCE/R1/Field1"), 3)
Len Function
Description
Determine the length of a string in characters or the number of
bytes required to store a variable
Return
Number of characters in a string expression or the number of
bytes required to store a variable
Return (Null)
Error: Incorrect argument count
Syntax
Len("strexpr")
Parameters
This function has the following parameters:
Name
Description
131
"strexpr"
Remarks
Any string expression. If a
string literal, enclose in
quotation marks.
Len("strexpr”
Len returns the number of characters in the argument strexpr.
Because Len works with user-defined data types, it is particularly
useful for determining the record length when you are
performing file input/output with random-access files.
However, if a user-defined data type contains variable-length
String elements, Len may not be able to properly determine the
actual number of storage bytes required.
If the argument to Len is null, the function returns a null.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
InStr Function
Example
This example shows how Len can be used to return the number
of bytes needed to store the data in Field2:
Len(FieldAt("/SOURCE/R1/Field2"))
Log Function
Description
Determine the natural logarithm of a number
Return
Natural logarithm of a number.=
Return (Null)
Incorrect argument count for function
Syntax
Log(number)
Parameters
This function has the following parameters:
Remarks
Name
Description
number
Any valid numeric expression
greater than zero.
The natural logarithm is the logarithm to the base e. The
constant e is approximately 2.718282.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
132
Functions
See Also
Log10 Function and Exp Function
Example
This example returns the natural logarithm of numbers in the
source ("Field1") to the target:
Log(FieldAt("/SOURCE/R1/Field1"))
Log10 Function
Description
Finds the base 10 logarithm of a number
Return
Base 10 logarithm of a number
Return (Null)
Error: Incorrect argument count
Syntax
Log10(number)
Parameters
This function has the following parameters:
Name
Description
number
Any valid numeric expression
greater than zero.
Remarks
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Log Function and Exp Function
Example
This example returns the base 10 logarithm of numbers in the
source ("Field1") to the target:
Log10(FieldAt("/SOURCE/R1/Field1"))
LogMessage Function
Note The MsgBox, InputBox, and InputBox$ functions are deprecated. Existing scripts using
any of these functions no longer display messages. Instead, MsgBox writes the message to the
log file. InputBox and InputBox$ log errors stating that the functions are not supported. Use
other functions, such as LogMessage, in place these deprecated functions.
133
Description
Creates an entry in the error and event log file while a transformation or
batch is running
Return
Not applicable for this function
Return (Null)
Error: Incorrect argument count
Syntax
LogMessage(ErrString, MsgString)
Parameters
This function has the following parameters:
Remarks
Name
Description
ErrString (required)
“ERROR”, “WARN”, “INFO”, and
“DEBUG” keyword labels for the
various LogMessage types. An
integer value representing the log
level appears in the log file. Enclose
in quotation marks if it is a string
literal.
MsgString (required)
Text of the message that appears in
the log. Enclose in quotation marks
if it is a string literal.
The maximum length of a message that can be returned by LogMessage
is 2048 bytes.
Note: You must select the types of messages you would like to write to the
transaction log file. Log messages generated by the LogMessage function
are displayed only if the corresponding error type is selected. (Search for
“logging” in the documentation.)
Example
If FieldAt("/SOURCE/R1/Account No") > 10019 Then
LogMessage("ERROR", "Account" & FieldAt("/SOURCE/R1/
Account No") & " number exceeds 10019")
End If
The above expression produces messages like the following in the error
and event log:
09/03/2003 12:31:45 Account 10030 number exceeds 10019
09/03/2003 12:31:45 Account 10031 number exceeds 10019
09/03/2003 12:31:45 Account 10032 number exceeds 10019
134
Functions
LTrim, LTrim$ Functions
Description
Trims leading spaces from a string
Note: The LTrim and LTrim$ functions are interchangeable.
Return
Specified string with leading (leftmost) spaces removed
Return (Null)
Error: Incorrect argument count
Syntax
LTrim[$](stringexpr)
Parameters
This function has the following parameters:
Remarks
Name
Description
stringexpr
Any expression containing
numeric or text characters. If a
string literal, enclose in
quotation marks.
LTrim(“stringexpr”)
LTrim removes leading spaces from a string.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
RTrim, RTrim$ Functions and Trim, Trim$ Functions
Example
The following example removes the leading spaces from the
string: " TestString":
LTrim(" TestString")
MacroExpand Function
Description
Expands macros embedded in a character string
Return
Expanded value of the specified macro
Return (Null)
Incorrect argument count for function
Syntax
MacroExpand[$](string)
Parameters
This function has the following parameters:
Name
Description
135
"string"
Remarks
Any expression containing
characters. If a string literal,
enclose in quotation marks.
MacroExpand(“$(string)”).
This function takes a character string and returns a string with all
macro occurrences expanded.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
DefineMacro Function, MacroValue Function, IsMacroDefined
Function, ClearMacro Function
Example
MacroExpand("$(mymacro)")
Return \myfolder\mysourcefiles\myfile.asc
C:\transformations\mymacro
MacroValue Function
136
Description
Looks up the value of a macro
Return
Defined value of a specified macro
Return (Null)
Error: Too few arguments for function
Syntax
MacroValue(macname [, default])
Parameters
This function has the following parameters:
Name
Description
macname (required)
String containing the name of
the macro. If not defined, then
default parameter is returned.
If a string literal, enclose in
quotation marks.
MacroValue(“macname”).
default (optional)
Default name of macro.
Returned if no macname
parameter is specified (must
be provided to be returned). If
no default is provided, an
empty string is returned.
Functions
Remarks
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
DefineMacro Function, IsMacroDefined Function, MacroExpand
Function, ClearMacro Function
Example
In this example, the defined macro called "mymacro" represents
the path to the source file. It returns the following path:
\myprocess\mysources\sourcefilename.asc:
MacroValue("mymacro")
MakeDirectory Function
Description
Creates a new directory
Return
Not applicable for this function
Return (Null)
Error: Incorrect argument count
Syntax
MakeDirectory(dirname)
Parameters
This function has the following parameters:
Remarks
Name
Description
dirname
A string containing the name
of the directory to create. If a
string literal, enclose in
quotation marks.
MakeDirectory(“dirname”).
If dirname contains a path, all directories up to the parent of the
new child directory must be included in the path and must exist.
An error is returned if a directory cannot be created. This is
usually because user permissions do not allow changes, a parent
directory does not exist, or the directory already exists.
See Also
GetDirectory Function and RemoveDirectory Function
Example
This expression creates a directory named xmlfiles:
MakeDirectory("C:\xmlfiles")
137
Mid, Mid$ Functions
Description
Returns a string that is part of some other string
Note: The Mid and Mid$ functions are interchangeable.
Return
Specified portion of a string
Return (Null)
Error: Too few arguments for function
Syntax
Mid[$](stringexpr, start[, length] )
Parameters
This function has the following parameters:
Remarks
Name
Description
stringexpr
String expression from which another
string is created. This can be any
string expression. If a string literal,
enclose in quotation marks.
Mid(“stringexpr”).
start
Long expression that indicates the
character position in stringexpr at
which the part to be taken begins.
length
Long expression that indicates the
number of characters to return.
The parameters start and length must be between 1 and approximately
65,500, inclusive. If length is omitted or if there are fewer than length
characters in the text (including the character at start), the Mid[$] function
returns all characters from the start position to the end of the string.
If start is greater than the number of characters in stringexpr, Mid[$] returns
a zero-length string.
Use the Len function to find the number of characters in stringexpr.
Caution: This function returns a value that must be used or stored to prevent
stack overflow. See Stack Overflow.
138
Functions
See Also
Left, Left$ Functions, Len Function, and Right, Right$ Functions
Example
The following expression will convert a yyyymmdd format string into a mm/
dd/yyyy format string:
Mid$(FieldAt("/SOURCE/R1/Field1"), 5, 2) & "/" &
Mid$(FieldAt("/SOURCE/R1/Field1"), 7, 2) & "/" &
Mid$(FieldAt("/SOURCE/R1/Field1"), 1, 4)
Note: If you want to use the above example, type the expression on one line.
The line breaks occur for display purposes only.
Minute Function
Description
Convert clock time to a minute integer
Return
Integer between 0 and 59, inclusive, which represents the
minute of the hour corresponding to the time provided as an
argument
Return (Null)
Error: Incorrect argument count
Syntax
Minute(number)
Parameters
This function has the following parameters:
Remarks
Name
Description
number
Any numeric expression that
can represent a date and/or
time from January 1, 100
through December 31, 9999,
where January 1, 1900 is 2.
Numbers to the left of the decimal point in number represent
the date; numbers to the right represent time. Negative
numbers represent dates prior to December 30, 1899.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Day Function, Hour Function, Now Function, Second Function,
Weekday Function, Year Function
139
Example
‘The example below returns the minute portion of the current
system time (if system time is 1:12:30, "12" is returned to the
target:
Minute(FieldAt("/SOURCE/R1/Field2")
The example below returns the minute portion from the source
("Minute"). The TimeValue function defines each time to be
time values, while the Minute function defines those values as
minutes:
a = TimeValue(Trim(FieldAt("/SOURCE/R1/
Minute")))
Minute(a)
Month Function
Description
Find the month integer of a date
Return
Integer between 1 and 12, inclusive, which represents the
month of the year for a date argument
Return (Null)
Error: Too few arguments for function
Syntax
Month(number)
Parameters
This function has the following parameters:
Remarks
Name
Description
number
The parameter number is any
numeric expression that can
represent a data and/or time
from January 1, 100 through
December 31, 9999, where
January 1, 1900 is 2.
Numbers to the left of the decimal point in number represent
the date; numbers to the right represent the time. Negative
numbers represent dates prior to December 30, 1899.
If number is null, this function returns a null.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
140
DatePart Function, Day Function, Hour Function, Minute
Function, Now Function, Second Function, Weekday Function,
Year Function
Functions
Example
This example will examine the data in the source field called
("ShipDate"), which contains a valid date, and return the twodigit month designation to the target field:
Month(FieldAt("/SOURCE/R1/ShipDate"))
The example below returns the month portion from dates in the
source ("ShipDate"). The DateValue function defines each date
as date values, while the Month function defines those values as
months:
a = DateValue(Trim(FieldAt("/SOURCE/R1/
ShipDate")))
Month(a)
NamePart Function
Description
Splits a name field, and returns the name parts to the same field in a
different order, or to a different field or fields
Return
Name parts first, middle, last, either to the same field in a different
order or to a different field or fields
Return (Null)
Error: Incorrect argument count
Syntax
NamePart([h] [f] [m] [mi] [l] [t], string)
Parameters
The following parameters can be used in this function:
Name
Description
h
Returns the honorific; for example, Mr. or Ms.
If a string literal, enclose in quotation marks.
NamePart(“h”).
f
Returns the first name. If a string literal,
enclose in quotation marks. NamePart(“f”).
m
Returns the middle name. If a string literal,
enclose in quotation marks. NamePart(“m”).
mi
Returns the middle initial. If a string literal,
enclose in quotation marks. NamePart(“mi”).
l
Returns the last name. If a string literal, enclose
in quotation marks. NamePart(“l”).
141
Remarks
t
Returns the title; for example, Jr. If a string
literal, enclose in quotation marks.
NamePart(“t”).
string
This is the search string from the source file. It
can be entered either as a specific string or as a
field name, such as ("FIELD1"). If a string literal,
enclose in quotation marks.
When a field in the source file contains a full name, it is sometimes
desirable to either rearrange the name in the same field in the target
file. Or split (parse) the full name into parts (honorific, first, middle, last,
title) and write each part to a separate field in the target file. You may
find that you need a title, honorific or prefix that is not in the list. To find
out how to customize the existing NamePart list, see Parsing a Name
Field Into Separate Fields.
For the supported parts, see below. For additional details, see Parsing a
Name Field Into Separate Fields .
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
142
Titles
Titles recognized by the NamePart function
include "PhD", "Sr", "Jr", "I", "II", "III", "IV", "V",
"MD" and "DO" and null. Also, anything three
or more characters in length and ending with a
period is considered a title.
Honorifics
Honorific names recognized by the NamePart
function include: “Professor”, “Sir”, “Doctor”,
“Mister”, “Mr”, “Mrs”, “Miss”, “Dr”, “Ms”,
“Rev” and null. Also, anything that is three or
more characters in length and ends with a
period is considered an honorific.
Last Name Prefixes
Last name prefixes recognized by the
NamePart function include: “Van”, “Van Der”,
“Von”, “Von Der”, “de”, “la” and null.
Functions
Letters "I" and "V"
The name parser reads the letters "I" and "V"
depending on what follows them, since they
can signify a first or middle initial or a title, such
as:
I = "The First"
V = "The Fifth"
If the letters "I" or "V" are followed by:
• A period or comma
• First or middle name or any word other than
a title
Then the they are considered initials.
Otherwise, they are treated as a title.
See Also
Add1Part Function, Add1Fmt Function, Add2Part Function, Parse
Function, Parsing a Name Field Into Separate Fields
Example
The following expression parses the "Name" field into separate fields in
a target file. The first name, middle name, last name and title (such as
Jr.) are all in one field called "Name" in the source file. Place each of the
following expressions in a separate field in the target:
NamePart("f",
NamePart("m",
NamePart("l",
NamePart(t"",
FieldAt("/SOURCE/R1/Name"))
FieldAt("/SOURCE/R1/Name"))
FieldAt("/SOURCE/R1/Name"))
FieldAt("/SOURCE/R1/Name"))
This expression rearranges a name in a single field, where the last name
is before the first name in a field called "Name" in the source file. In this
case, the "first name-last name" order is returned to the target file:
NamePart("f l", FieldAt("/SOURCE/R1/Name") )
Parsing a Name Field Into Separate Fields
If a name field source data file contains parts of a name that you want to separate, use the
NamePart function to do the following:
• Parse a name field into separate fields
• Rearrange order of a name in the same field
• Create a name part custom file
Prepare to parse the field by first doing the following:
• Locate the source field that contains the data to be parsed.
• Determine the number and position of the target fields needed.
• Set up or select the fields in your target file to which the parsed data is written.
143
After you have completed the planning, write an expression to tell the map which portion
of the parsed data goes into each target field.
Target Field Name
Target Expression
Honorific
= NamePart("h", FieldAt("/SOURCE/R1/Name"))
First Name
= NamePart("f", FieldAt("/SOURCE/R1/Name"))
Middle Name
= NamePart("m", FieldAt("/SOURCE/R1/Name"))
Middle Initial
= NamePart("mi", FieldAt("/SOURCE/R1/Name"))
Last Name
= NamePart("l", FieldAt("/SOURCE/R1/Name"))
Title
= NamePart("t", FieldAt("/SOURCE/R1/Name"))
In the example above, the source field that contains the full name is ("Name"). The fields
in the target file that contain the name "parts" have been given field names that match the
corresponding part of the name. The target expression in each of the fields has been
written to instruct the map to place a specific name "part" in that field in the target data
file.
Where "f" places the first names in the First Name field, "m" places the middle initial (or
name) in the Middle Initial field, and "l" places the last name in the Last Name field, etc.
After the transformation is run, the names in every record are parsed into the separate
fields in the target data file.
Example of Rearranging Order of a Name
There may be some instances where you need to reverse the order of the first and last
names in a field that contains a full name. For example, the name appears in your source
data file as Smith John, and you want the name to appear as John Smith in your target file.
You can write an expression for that field as follows.
Target Field Name
Target Expression
Name
= NamePart("f l", FieldAt("/SOURCE/R1/NAME"))
Where ("NAME") is the field name in your source file that contains the person's name. And
"f l" instructs the map to position the name in "firstname lastname" order in the Name
field in your target file.
After the transformation is run, the names are in "firstname lastname" order in every
record in your target data file.
144
Functions
Tip Any string that is three or more characters in length and ends with a period can be
considered an honorific.
Now Function
Description
Returns the local computer’s date/time
Return
Date that represents the current date and time
according to the setting of the computer's
system date and time. You may substitute
TimeStamp for Now, as both have the same
syntax.
Return (Null)
Not applicable for this function
Syntax
Now( )
Parameters
None required, however, the open and close
parentheses after Now are required.
Remarks
The Now Function returns a date containing a
date and time that are stored internally as a
double-precision number. This number
represents a date and time from January 1, 100
through December 31, 9999, where January 1,
1900 is 2. Numbers to the left of the decimal
point represent the date; numbers to the right
represent the time.
Caution: This function returns a value that must
be used or stored to prevent stack overflow.
See Stack Overflow.
See Also
Day Function, Hour Function, Hour Function,
Minute Function, Month Function, Second
Function, Weekday Function, Year Function
Example
These examples return a date/time value to the
target field:
Now()
or use TimeStamp for the same result:
TimeStamp()
145
Null Function
Description
Returns a null value
Return
Null value
Return (Null)
Not applicable
Syntax
Null
Parameters
This function has no required parameters.
Remarks
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
Example
To insert a null value in a field, enter the following expression:
Null
Oct Function
Description
Print a number to a string in octal representation.
Return
String representing the octal value of a number.
Return (Null)
Error: Incorrect argument count
Syntax
Oct (number)
Parameters
This function has the following parameters:
Remarks
Name
Description
number
Any numeric expression.
If number is not already a whole number, it is rounded to the
nearest whole number before being evaluated.
You can represent octal numbers directly by preceding numbers
in the proper range with &O. For example, &O10 is the octal
notation for decimal 8.
146
If number is
Oct Returns
Null
Null
Empty
Zero (0)
Functions
Any other number
Up to 11 octal characters
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Hex Function
Example
Dim MyOct
MyOct = Oct (4) ' Returns 4.
MyOct = Oct (8) ' Returns 10.
MyOct = Oct (459) ' Returns 713.
Parse Function
Description
Splits (parses) a string of data in one field on a designated
character
Return
Parsed "parts" to a different field or fields. (UnString can be
substituted for Parse, as both have the same syntax.)
Return (Null)
Error: Too few arguments for function
Syntax
Parse(number, string, character)
Parameters
This function has the following parameters:
Name
Description
number
Indicates which "part" or
section of the parsed data you
want to return. "1" indicates
the first part, "2" indicates the
second part, "3" indicates the
third part, etc.
string
Indicates the string expression
to parse. If a string literal,
enclose in quotation marks.
character
Indicates the character on
which to parse. If a string
literal, enclose in quotation
marks.
147
Remarks
The Parse function enables the user to parse the data in one
field in the source file and write the "parts" of the data to a field
or fields in the target file. Parsing is done on a unique character,
such as a space, an asterisk, a dash, etc. It is important to
understand that if you parse on a character that is part of the
actual data, undesirable results may occur.
Be careful to observe case when using a function that performs
a string-search. String-search Functions are case-sensitive,
literal searches. A Function that searches for "x" disregards "X".
If the function has an optional argument "compare", and you do
not use the optional compare argument, the expression is casesensitive by default.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Add1Part Function, Add1Fmt Function, Add2Part Function,
NamePart Function
For additional details, see Example of Parsing a Source Field by
Character.
Example
The following example parses a field in the source file called
("FIELD1") on a space, and writes each of the three "parts" of the
parsed data into three fields in the target file:
Parse(1, FieldAt("/SOURCE/R1/FIELD1"), " ")
Parse(2, FieldAt("/SOURCE/R1/FIELD1"), " ")
Parse(3, FieldAt("/SOURCE/R1/FIELD1"), " ")
148
Functions
The Parse function is useful for stripping out data, as in the
instance below, the word "Or". The source contains data like
"Mr. John Q. Smith Or Mrs. John Q. Smith", so the expression
finds the "Or" within the data and concatenates the names with
a space between them:
Parse(1, FieldAt("/SOURCE/R1/Field1"), "Or") & "
" & Parse(2, FieldAt("/SOURCE/R1/Field1"), "Or")
You can also use hex values within a Parse function expression.
The following expression parses the Address field on any blank
(hex value 20). The "Chr(&h20)" portion of the expression
satisfies the character parameter for the Parse function:
Parse(1, FieldAt("/SOURCE/R1/Address") ,
Chr(&h20))
or
TimeStamp(1, FieldAt("/SOURCE/R1/Address") ,
Chr(&h20))
Example of Parsing a Source Field by Character
Sometimes you want to parse data in a field that is not name or address data. The Parse
function allows the user to parse one source field into two or more target fields by a
particular character or characters in the source field.
Some common characters to parse by are: a space, "," (comma), "*" (asterisk), or "/"
(slash). However, any printable character can be used to parse the data. So, if you parse by
a character that is part of the actual data, you may get undesirable results.
To prepare for parsing, make sure you do the following:
• Locate the source field in the map that contains the data to be parsed.
• Determine which character you will use to parse the data.
• Map the target fields to which the parsed data is written.
Now, write an expression in each mapped target field that detects the character and then
writes the correct portion of data to that field.
The following scenario illustrate how you may use the Parse function to parse the data in
one source field into two separate fields in your target file.
A Customer field in your source file contains a region code (ABC), an '*' (asterisk), and a
customer number (10019). For example: ABC*10019. The region code and customer code
are always separated by an * but each code could be more than three to five letters. In
your target file, you want the region code to be in one field called REGION, and the
customer number in another field called CUSTOMER NO.
149
Insert an additional field in the desired position within the map. Then, write a target field
expression in each of the two fields to instruct the map to parse the data and place each
"section" of the parsed data in that field in the target data file.
Target Field Name
Target Field Expression
Region
= Parse(1, FieldAt("/SOURCE/R1/Customer"), "*")
Customer No
= Parse(2, FieldAt("/SOURCE/R1/Customer"), "*")
The data in the "Customer" field in the source file is being parsed on the "*" (asterisk). The
"1" in the top expression places the first "section" of the parsed data in the Region field,
and the "2" in the bottom expression places the second "section" of the parsed data in the
Customer No field in the target data file.
If you need to parse a field on more than one character, the syntax is as follows:
Parse(number, "string", "char1", "char2", ...).
ParseXML Function
Description
Parses an XML document in a string and returns a DOM object
Return
DOM object with DOM tree of subject file
Return (Null)
Error: Invalid use of reserved word
Syntax
ParseXML(xml)
Parameters
This function has the following parameters:
Remarks
Name
Description
xml
A variable representing a
string that contains an XML
document. If a string literal,
enclose in quotation marks.
ParseXML(“xml”)
The string is a byte representation of the XML document. The
string can contain any valid XML characters.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
150
Functions
See Also
ParseXMLFile Function
Example
Dim doc as DOMDocument
Dim xml
xml="<abc><def>text</def></abc>"
Set doc = ParseXML(xml)
ParseXMLFile Function
Description
Parses an XML document in a file
Return
DOM object
Return (Null)
Error: Invalid use of reserved word
Syntax
ParseXMLFile(filename)
Parameters
This function has the following parameters:
Remarks
Name
Description
"filename"
Name of the xml file to parse.
If a string literal, enclose in
quotation marks.
ParseXMLFile(“filename”).
The xml file represented by filename may also be a URI. For
details, search for “URI” in the documentation.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
ParseXML Function
Example
Dim doc as DOMDocument
Set doc = ParseXMLFile("C:\testfile.xml")
Print Function
Description
Prints specified string in standard output to the display screen
Return
Not applicable for this function
Return (Null)
Error: Incorrect argument count
151
Syntax
Print[StdOut]
Parameters
This function has the following parameters:
Name
Description
stdout
Optional. Expression or list of
expressions resulting in a
string to Print. If omitted, a
blank line is printed.
Remarks
Print function takes one required parameter, an expression
resulting in a string to print. It is written to StdOut. Output can
be a numeric or string expression. If StdOut parameter is not
used, put open and close parentheses after Print, such as the
following: Print()
Example
Dim MyText
MyText = "Output message to the immediate
window."
Print(FieldAt("/SOURCE/R1/Status") & [MyText])
RecordAt Function
Description
Translates a record address to a DJRecord object reference
Return
DJRecord object
Return (Null)
Syntax
RecordAt(path)
Parameters
This function has the following parameters:
Remarks
Name
Description
path
Path to a DJRecord object.
You can use any of the DJRecord variable properties with
RecordAt, as follows:
RecordAt("/SOURCE/R1").property
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
152
Functions
See Also
FieldAt Function
DJRecord Object Type
Example
This example returns the name of record R1:
RecordAt("/SOURCE/R1").Name
Reject Function
Description
Set a condition under which records are rejected from the
transformation or process
Return
Rejected records are written to a Reject file or table
Return (Null)
Error: Incorrect argument count
Syntax
Reject(number)
Parameters
This function has the following parameters:
Remarks
Name
Description
n (optional)
Any valid numeric expression
Configuring a reject connection is optional.
To write reject records, you must add an OutputRecord action to
a RecordRejected event on a second control link.
If you use no reject connection, the transformation discards
reject records. See Discard Function for details.
153
See Also
Abort Function, Discard Function
See “transformation events”, “record events”, and “reject
record” in the documentation.
Example
Tip: You can find a reject sample on the web site.
You must create a reject file and connection string.
In this example, if ("Field1") is empty, then this record is written
to the reject file, not to the target file. All other records are
transformed and written to the target file:
If FieldAt("/SOURCE/R1/Field1") = "" Then
Reject()
In the following example, if ("Field1") contains the text
"General" and if Field2 is greater than or equal to 10050, then
this record is written to the Reject file. All other records are
transformed and written to the target file:
If FieldAt("/SOURCE/R1/Field1") = "General" and
(FieldAt("/SOURCE/R1/Field2") >= 10050) then
Reject()
RemoveDirectory Function
Description
Deletes a directory with a specified name
Return
Not applicable for this function
Return (Null)
Error: Incorrect argument count
Syntax
RemoveDirectory(dirname)
Parameters
This function has the following parameters:
Remarks
154
Name
Description
"dirname"
A string containing the name
of the directory to create. If a
string literal, enclose in
quotation marks.
RemoveDirectory(“dirname”)
None.
Functions
See Also
GetDirectory Function and MakeDirectory Function
Example
Delete a directory called MyFiles:
RemoveDirectory("C:\MyFiles")
Right, Right$ Functions
Description
Reads and returns the rightmost characters of a string
Note: The Right and Right$ functions are interchangeable.
Return
Rightmost characters of a string
Return (Null)
Error: Incorrect argument count
Syntax
Right[$](strexpr,n)
Parameters
This function has the following parameters:
Remarks
Name
Description
strexpr
Any string expression. If a
string literal, enclose in
quotation marks.
n
A Long expression indicating
how many characters to
return. It must be between 0
and approximately 65,500,
inclusive. If n is 0, the return
value is a zero-length string. If
n is greater than or equal to
the number of characters in
strexpr, the entire string is
returned.
Right[$] returns a String.
The argument n is a Long expression indicating how many
characters to return. It must be between 0 and approximately
65,500, inclusive. If n is 0, the return value is a zero-length string.
If n is greater than or equal to the number of characters in
strexpr, the entire string is returned.
To find the number of characters in strexpr, use Len(strexpr).
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
155
See Also
Left, Left$ Functions, Len Function, Mid, Mid$ Functions
Example
This example returns the three rightmost characters of the
source field ("Field1"):
Right(FieldAt("/SOURCE/R1/Field1"), 3)
Rnd Function
Description
Returns a random number
Return
This function returns a Single value less than 1 but greater than
or equal to 0 (zero).
Return (Null)
Error: Incorrect argument count
Syntax
Rnd(number)
Parameters
This function has the following parameters:
Remarks
156
Name
Description
number
Any valid numeric expression.
The value of number determines how Rnd generates a random
number. See the table below:
Value of number:
Number returned:
<0
The same number every time,
as determined by number.
>0
The next random number in
the sequence.
=0
The number most recently
generated.
number omitted
The next random number in
the sequence.
Functions
This function does not generate random numbers. Instead, like
most random number generators, it starts off with a seed value
that is used to calculate the next psuedo-random number. One
of the benefits of using a seed value is that using the same seed
value can reproduce the sequence of random numbers. This is
important for testing systems that rely on the random number
generators. If you need more random values, you can begin the
seed value with one generated by the system clock.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Abs Function, Fix Function, Int Function, Sgn Function
Example
Rnd(37)
Place this expression in the BeforeTransformation event, so it is
only executed once at the beginning of the transformation:
Rnd(10000 * (Fix(Now()) - Now()))
Round Function
Description
Round a number
Return
Number rounded to a specified number of decimal places
Return (Null)
Error: Too few arguments for function
Syntax
Round (expression [, numdecimalplaces])
Parameters
This function has the following parameters:
Name
Description
expression (required)
Numeric expression being
rounded.Enclose in quotation
marks only if it is a string
literal. Round(“expression”).
numdecimalplaces (optional)
Number indicating how many
places to the right of the
decimal are used in rounding.
If omitted, integers are
returned by the Round
function.
157
Remarks
The Round function rounds a floating- or fixed-point decimal to
a specified number of places.
Although the Round function is useful for returning a number
with a specified number of decimal places, you can't always
predict how it will round when the rounding digit is a 5.
Rounding of a number depends on the internal binary
representation of that number. See example.
When the digit being rounded is 5, rounding is based on the
previous digit. If the digit that precedes 5 is even, the number is
preserved. If the digit that precedes 5 is odd, the number is
rounded up. The rounding methods always preserve even
numbers, while odd numbers are changed to the next highest
even number.
You can use the Option Math Precise or Option Math Strict
statement to force numbers to be represented as decimal values
where possible. These statements eliminate the imprecision of
binary floating point value for a performance trade-off. See
Option Math Statements.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Fix Function and Int Function
Example
Round(1.2335, 3) and Round(1.2345, 3) should both return
1.234. The 3 represents the number of decimal places:
Round(1.2345, 3)returns 1.234
Round(1.2335, 3)returns 1.234
RTrim, RTrim$ Functions
Description
Trims trailing spaces from a string
Note: The RTrim and RTrim$ functions are interchangeable.
Return
Specified string with trailing (rightmost) spaces removed
Return (Null)
Error: Incorrect argument count
Syntax
RTrim[$](stringexpr)
Parameters
This function has the following parameters:
Name
158
Description
Functions
stringexpr
Any expression containing
numeric or text characters. If a
string literal, enclose in
quotation marks.
RTrim(“stringexpr”).
Remarks
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
LTrim, LTrim$ Functions and Trim, Trim$ Functions
Example
The following example removes the trailing spaces from the
string "TestString ":
RTrim("TestString ")
Second Function
Description
Convert clock time to second
Return
Integer between 0 and 59, inclusive, which represents the
second of the day corresponding to the time provided as an
argument
Return (Null)
Error: Incorrect argument count
Syntax
Second(number)
Parameters
This function has the following parameters:
Remarks
Name
Description
number
Any numeric expression that
can represent a date and/or
time from January 1, 100
through December 31, 9999,
where January 1, 1900 is 2.
Numbers to the left of the decimal point in number represent
the date; numbers to the right represent the time. Negative
numbers represent dates prior to December 30, 1899.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
DatePart Function, Day Function, Hour Function, Minute
Function, Month Function, Now Function, Weekday Function,
and Year Function
159
Example
This example returns the second portion of the current system
time (if system time is 1:12:30, "30" is returned to the target:
Second (FieldAt("/SOURCE/R1/Field1") )
The example below returns the second portion from the source
("Second"). The TimeValue function defines each time to be time
values, while the Second function defines those values as
minutes:
a = TimeValue(Trim(FieldAt("/SOURCE/R1/
Second")))
Second(a)
Serial Function
Description
Write serial values. You may substitute Increment for Serial, as
both have the same syntax.
Return
Next serial value of a numeric expression
Return (Null)
Error: Incorrect argument count
Syntax
Serial(number)
Parameters
This function has the following parameters:
Remarks
Name
Description
number
Any valid numeric expression.
For more details, see Remarks.
The Serial function returns the next serial value.
If number is provided, it sets the starting serial number. Notice
that Serial returns the NEXT serial value. This means number
must be entered as the desired starting value LESS ONE.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
160
Functions
Example
The following example writes an incremental number in a field
for every record, starting with the number '1':
=Serial(0)
or
=Increment(0)
The following example writes an incremental number in a field
for every record, starting with the number '223':
Serial(222)
or
Increment(222)
Sgn Function
Description
Find the sign of a supplied number
Return
Value indicating the sign of a number
Return (Null)
Error: Incorrect argument count
Syntax
Sgn(number)
Parameters
This function has the following parameters:
Remarks
Name
Description
number
Any valid numeric expression.
The number parameter sign determines the value returned by
the Sgn function:
If number > 0, Sgn(number) returns 1.
If number = 0, Sgn(number) returns 0.
If number < 0, Sgn(number) returns -1.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Abs Function, Fix Function, and Int Function
161
Example
This expression returns a –1, since the result is < 0:
Sgn(0-1)
This expression returns a 1, since the result is > 0:
Sgn(0+2)
Shell Function
The Shell function is available only if your administrator has enabled the ability to call
executables.
162
Description
Run an external command, specified on command line
Return
Not applicable for this function
Return (Null)
Error: Too few arguments for function
Syntax
Shell(command-line [, style] [, wait])
Parameters
This function has the following parameters:
Name
Description
"command-line"
The complete path of the
executable to run. If a string
literal, enclose in quotation
marks. Shell(“command-line”).
Functions
style (required only with wait)
Value to set the style of
window in which to run the
program. If omitted, Shell uses
minimized focus (value 2),
which starts the program
minimized and with focus.
0 - Hidden
1 - Normal focus
2 - Minimized focus
3 - Maximized focus
4 - Normal; no focus; window
is restored to its most recent
size and position; currently
active window remains active
5 - Minimized; no focus;
currently active window
remains active
wait (optional)
Remarks
Boolean 0 (false) or -1 (true) to
indicate whether Shell waits
for completion of the program.
If omitted, false by default.
Can run any executable program. When wait is false, other
processes can start before the executable has finished, in which
case it returns 0, otherwise the return is the exit code of the
program being run.
If you run a .bat file, you cannot use the following syntax:
Shell("file.bat")
Instead, use the following:
Shell("cmd /c file.bat")
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Sleep Function
Example
Shell("C:\Program Files\TextPad
4\TextPad.exe",1)
163
SignFlip Function
Description
Moves the sign operator from the front of a string to the end, or
from the end of the string to the front
Return
Numeric string with the sign moved to the opposite end of the
supplied numeric string
Return (Null)
Error: Incorrect argument count
Syntax
SignFlip("string")
Parameters
This function has the following parameters:
Remarks
Name
Description
"string" (required)
String with a sign operator (+, ) at the front of the string or at
the end of the string. If a string
literal, enclose in quotation
marks. SignFlip(“string”)
If no sign operator (+, -) exists in the string, the function returns
the string "as is".
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Arithmetic Operators
Example
SignFlip("-36.09")
Sleep Function
Description
Put a program into a wait state for a specific number of
milliseconds
Return
Not applicable for this function
Return (Null)
Error: Incorrect argument count
Syntax
Sleep(milliseconds)
Parameters
This function has the following parameters:
Name
164
Description
Functions
milliseconds
The number of milliseconds to
sleep (1000 milliseconds = 1
second, i.e. a value of 3500
means sleep for 3.5 seconds).
No value is returned.
Remarks
You can use this function when you need a delay when running
a transformation or process. Since there is no return value, if you
want to monitor this function, you can use the LogMessage
function to determine when the delay has terminated. Sleep is
more accurate than using a do-nothing loop and waiting for a
certain amount of time to pass.
See Also
Shell Function
Example
This expression causes your program to sleep for 3,500
milliseconds:
Sleep(3500)
SortArray Function
Description
Sort an array
Return
Not applicable for this function
Return (Null)
Error: Too few arguments for function
Syntax
SortArray(array [, ignorecase [, rev] [, style]])
Parameters
This function has the following parameters:
Name
Description
array (required)
An array variable
ignorecase (optional)
Ignore case sensitivity
rev (optional)
Sorting is in reverse order
style (optional)
Sort multi-diminsional arrays
as column-major
165
Remarks
The first parameter must be an array variable (if not, a
TYPEMISMATCH error is returned).
If ignorecase is true, sorting of string values will ignore case. This
is an optional parameter, and its default value is FALSE.
If rev is true, sorting is in reverse order (from largest to smallest).
This is an optional parameter, and its default value is FALSE.
The style parameter default is 0. If this parameter is omitted or
unknown, the return is sorted as a one-dimensional array. When
the style parameter is set to 1, the multidimensional array is
sorted as column-major. The column-major sort returns results
ordered by the first value in a row or plane. This value
determines the position of the entire row or plane.
Example
The following expression sorts MyArray by the first element:
SortArray(MyArray)
Space, Space$ Functions
Description
Returns a string consisting of a specified number of spaces.
Note: The Space and Space$ functions are interchangeable.
Return
White spaces specified by n
Return (Null)
Error: Incorrect argument count
Syntax
Space[$](number)
Parameters
This function has the following parameters:
Name
Description
number
Specifies the number of spaces you
want in the string. It can be any
number between 0 and
approximately 65,000, inclusive.
Remarks
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
See Also
String, String$ Functions
Example
This example adds three spaces before the data in source field ("Field1"):
Space(3) & FieldAt("/SOURCE/R1/Field1")
166
Functions
This example concatenates ("Field1") and ("Field2") source fields, and
adds one (1) space between the concatenated data in the same target
field:
FieldAt("/SOURCE/R1/Field1") & Space(1) & FieldAt("/
SOURCE/R1/Field2")
This example creates a report title with 65 spaces before the text begins:
Space(65) & "Accounts Receivables Report"
Split Function
Description
Parse a string
Return
Zero-based, one-dimensional array containing a specified number of
substrings
Return (Null)
Error: Invalid expression syntax
Syntax
Split(expression[, delimiter[, limit[, compare]]])
Parameters
This function has the following parameters:
Name
Description
expression (required)
String expression containing
substrings and delimiters. If
expression is a zero-length
string(""), Split returns an empty
array, that is, an array with no
elements and no data.
delimiter (optional)
String character used to identify
substring limits. If omitted, the
space character (" ") is assumed to
be the delimiter. If delimiter is a
zero-length string, a single-element
array containing the entire
expression string is returned.
limit (optional)
Number of substrings to be
returned; –1 indicates that all
substrings are returned.
167
compare (optional)
Remarks
Numeric value indicating the kind
of comparison to use when
evaluating substrings. A value of 0
performs a binary comparison,
while a value of 1 will perform a
textual comparison.
You can assign arrays to arrays with this function.
Tip: The function is similar to the Parse function, however, Split is superior
in performance. The Parse Function has to run every time it is used; in
contrast, after one Split, you can directly address the results from the
array in memory from that point on.
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
See Also
Join Function, Filter Function, and Parse Function
Example
Declare variable MyArray, and set it equal to the field where the values
are located:
Dim MyArray(10)
MyArray = Split(FieldAt("/SOURCE/R1/Field1"), " ")
Str, Str$ Functions
Description
Convert a numeric value to a text string
Note: The Str and Str$ functions are interchangeable.
168
Return
String representation of the value of a numeric expression
Return (Null)
Error: Incorrect argument count
Syntax
Str[$](number)
Parameters
This function has the following parameters:
Name
Description
number
Any numeric expression.
Functions
Remarks
When numbers are converted to text, a leading space is always
reserved for the sign of number. If number is positive, the string
returned by Str[$] contains a leading blank and the plus sign is
implied. In contrast, the Format[$] Function does not include a
leading blank space.
Str[$] returns a String. Use Str[$] to convert simple numeric
values to strings. Use the Format[$] Function to convert numeric
values you want formatted as dates, times, or currency or in
other user-defined formats.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
DateValMask Function, Format, Format$ Function, Val Function,
ValMask Function
Example
This example returns the number 459 as a string representation.
The Hex Browser interprets the string 459 as "20 34 35 39". The
"20" represents the leading space reserved for the sign of the
number:
Str(459)
StrComp Function
Description
Compare two string arguments
Return
Value that represents the result of a comparison of two string
arguments
Return (Null)
Error: Too few arguments for function
Syntax
StrComp("strexpr1", "strexpr2" [,[compare])
Parameters
This function has the following parameters:
Name
Description
"strexpr1" (required)
The first string argument.
"strexp2" (required)
The second string argument.
169
compare (optional)
Remarks
Specifies the stringcomparison method. This
value must be 0 or 1. If
compare is 0, the string
comparison is case-sensitive. If
compare is 1, stringcomparison is not casesensitive.
This function returns a value that indicates the relationship
between the string expressions. If strexpr1 is less than strexpr2,
-1 is returned. If strexpr1 equals strexpr2, 0 is returned. If
strexpr1 is greater than strexpr2, 1 is returned.
Tip: You may substitute StrComp for Compare, as they are
identical in syntax.
Be careful to observe the case when using a function that
performs a string-search. String-search functions are casesensitive, literal searches. A function that searches for "x"
disregards "X". If the function has an optional parameter
"compare", and you do not use the optional compare
parameter, the expression is case-sensitive by default.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
StrReplace Function
Example
This example compares "fed" and "FED" and requires the stringcomparison to be case-sensitive by indicating "(0)" as the
compare. It returns "1", since the text strings are mixed case:
StrComp("fed", "FED", (0))
If a (1) compare is substituted in the expression above, a 0 is
returned to the target, indicating that the text strings are the
same (case-sensitivity is ignored).
String, String$ Functions
Description
Returns a string consisting of a specified number of occurrences
of a specified character.
Note: The String and String$ functions are interchangeable.
170
Return
String consisting of a specified number of occurrences of a
specified character.
Return (Null)
Incorrect argument count for function.
Functions
Syntax
String[$](number, string)
Parameters
This function has the following parameters:
Name
Description
number
Numeric expression indicating
the length of the returned
string. Number must be
between 0 and 65,535
inclusive.
string
String expression where the
first character is used to build
the return string.
To convert numeric values
greater than 255 to an ANSI
code between 0 and 255,
String[$] uses the remainder
after the value is divided by
256 (argument Mod 256).
Remarks
String[$] returns a String. Use String[$] to create a string that
consists of one character repeated over and over.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Space, Space$ Functions
Example
In the following example, String returns a string consisting of 8
asterisks by replicating the character provided by the second
argument:
String(8, "*")
StrReplace Function
Description
Replaces one literal string with another literal string
Return
Newstring argument
Return (Null)
Error: Too few arguments for function
Syntax
StrReplace(oldstring, newstring, string, [occurrences])
Parameters
This function has the following parameters:
Name
Description
171
Remarks
oldstring (required)
The literal string to be
replaced. If a string literal,
enclose in quotation marks.
StrReplace(“oldstring”).
newstring (required)
The literal string to replace
oldstring. If a string literal,
enclose in quotation marks.
StrReplace(“newstring”).
string (required)
The search string. May be
entered as a field name. If a
string literal, enclose in
quotation marks.
StrReplace(“string”).
occurrences (optional)
Controls the number of strings
replaced. If a string literal,
enclose in quotation marks.
StrReplace(“occurences”)
Be careful to observe case when using a function that performs
a string-search. String-search functions are case-sensitive, literal
searches. A function that searches for "x" disregards "X". If the
function has an optional argument "compare", and you do not
use the optional compare argument, the expression is casesensitive by default.
The StrReplace function is similar to Sub/GSub functions with
the following differences:
• The replacement text (oldstring and newstring) is expressed as
literal strings only. No regular expression metacharacters can
be used. For examples of these metacharacters, see Regular
Expressions.To use metacharacters in an expression, use the
GSub Function instead.
• The number of strings replaced can be controlled by the
optional fourth parameter occurrences;
It supports the substitution of individual binary characters. If
the occurrences parameter is omitted, then all occurrences of
oldstring are replaced with newstring, since global replaces are
probably one of the most common string operations.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
172
GSub Function, LTrim, LTrim$ Functions, Select Case...End Case
Statement, Sub Function, Transliterate Function
Functions
Example
StrReplace("abc", "ABC", "abcdefg")
returns "ABCdefg" – all occurrences
StrReplace("abc", "ABC", "abc/xyz/abc/xyz/abc")
returns "ABC/xyz/ABC/xyz/ABC" – all occurrences
StrReplace("abcdefg", "ABC", "abcdefg")
returns "ABC" – all occurrences
StrReplace("TX", "Texas", FieldAt("/SOURCE/R1/
FIELDNAME"))
returns "Texas" for all occurrences of "TX" in ("/SOURCE/R1/
FIELDNAME")
StrReplace(Chr(00), "", FieldAt("/SOURCE/R1/
FIELDNAME"))
replaces nulls with nothing in all occurrences.
The following example searches for the words "Drive", "Lane",
"Avenue", "Street", and "Road" in Field1 in the source file, and
replaces each, respectively, with the abbreviations "Dr", "Ln",
"Ave", "St", and "Rd" in the target file:
StrReplace("Drive", "Dr", StrReplace("Lane",
"Ln", StrReplace("Avenue", "Ave",
StrReplace("Street", "St", StrReplace("Road",
"Rd", FieldAt("/SOURCE/R1/Address"))))))
StrReverse Function
Description
Reverse the order of a string
Return
String in which the character order of a specified string is
reversed
Return (Null)
Error: Incorrect argument count
Syntax
StrReverse("expression")
Parameters
This function has the following parameters:
Name
Description
"expression"
The string whose characters
are to be reversed.
173
Remarks
If expression is a zero-length string (""), a zero-length string is
returned. If expression is null, an error occurs.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
Example
The following expression returns the string gnirts (the string
example "string" reversed):
StrReverse("string")
Sub Function
Description
Within a string, replace the first instance of a substring with another.
Return
See Remarks.
Return (Null)
Error: Incorrect argument count
Syntax
Sub(oldstring, newstring, (fieldname))
Parameters
This function has the following parameters:
174
Name
Description
oldstring (required)
The original string. If a string literal,
enclose in quotation marks.
newstring (required)
The replacement string. If a string
literal, enclose in quotation marks.
fieldname (required)
Any string expression. If a string literal,
enclose in quotation marks.
Functions
Remarks
Sub replaces the first instance of oldstring with newstring in an existing string
found within one field of data.
Escape Special Characters. Sub recognizes all special characters in the "oldstring"
parameter, but they must be escaped. See Example 1 for an expression that
escapes the special characters "(" and ")". For more information on regular
expression and escaping special characters, see Regular Expressions.
Limitation: If you attempt to use this function on very large strings (50K and
above), you may experience a performance hit. To avoid long run times of your
transformations, do not use Sub on very large strings.
Tip: You may substitute Replace for Sub, since both are identical in syntax.
Be careful to observe case when using a function that performs a string-search.
String-search Functions are case-sensitive, literal searches. A function that
searches for "x" disregards "X". If the function has an optional argument
"compare", and you do not use the optional compare argument, the expression is
case-sensitive by default.
Caution: This function returns a value that must be used or stored to prevent
stack overflow. See Stack Overflow.
See Also
GSub Function, InitCaps Function, LCase, LCase$ Functions, LTrim, LTrim$
Functions, StrReplace Function, UCase, UCase$ Functions
Example 1
How to escape special characters – You may not think that the parentheses are
special characters. However, to replace parentheses with this function,
parentheses (and all special characters) must be escaped to be recognized.
The '(' and ')' characters are used for grouping in regular expressions. The
expression "(abc)" matches one or more occurrences of the string abc. If you want
to search for the literal characters '(' and ')', you need to escape them with the
backslash symbol \.
If you want to find the first instance of parentheses and replace them with
another character, you need to use the escape character backslash "/". Below, the
first instance of "(" and ")" in Field1 are replaced by an empty string in the target:
Sub("\(", " ", Sub("\)", " ", FieldAt("/SOURCE/R1/Field1")))
Example 2
This example replaces the first instance of "Avenue" with "Ave." in the Address
field:
Sub("Avenue", "Ave.", FieldAt("/SOURCE/R1/Address"))
175
Switch Function
Description
Evaluate a list of expressions
Return
Value or an expression associated with the first expression in the
list that is True
Return (Null)
Error: Incorrect argument count
Syntax
Switch(strexpr1, str1 [, strexpr2, str2...[strexpr7, str7]] )
Parameters
This function has the following parameters:
Remarks
Name
Description
strexpr
Expression you want to
evaluate. A maximum of seven
instances of this parameter is
allowed. If a string literal,
enclose in quotation marks.
Switch(“strexp”).
str
Value or expression that is
returned if the corresponding
strexpr is True. If a string
literal, enclose in quotation
marks. Switch(“strexp”
,“str1”).
The Switch function evaluates the string expression in the
strexpr list and returns the contents of the first str argument
whose corresponding strexpr expression evaluates True. For
example, if strexpr1 is True, Switch returns str1. If strexpr1 is
False, but strexpr2 is True, Switch returns str2, and so on.
Switch returns a null if:
• None of the strexpr expressions is True.
• The leftmost strexpr that is True has a corresponding str that is
null.
Switch evaluates all of the expressions, even though it returns
only one of them. For this reason, watch for undesirable results.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
176
Functions
See Also
Choose Function, GSub Function, IIf Function, LTrim, LTrim$
Functions, Sub Function
Example
In this example, the source field ("City") is evaluated for the text
strings "Mad" and "Mon". If "Mad (Madrid)" is True, "Spain" is
returned. If "Mon (Monterrey)" is true, "Mexico" is returned. If
neither of these conditions are true, "US" is returned to the
target field:
Switch(FieldAt("/SOURCE/R1/City") Like "Mad",
"Spain", FieldAt("/SOURCE/R1/City") Like "Mon",
"Mexico", FieldAt("/SOURCE/R1/City") <> "Mad" OR
"Mon", "US")
Terminate Function
Description
Causes the transformation to terminate based on a specified condition.
Return
Not applicable; terminates a transformation pending the outcome of a
user-defined integer expression.
Return (Null)
Error: Incorrect argument count
Syntax
Terminate(number)
Parameters
This function has the following parameters:
Remarks
Name
Description
n (optional)
Any valid numeric expression.
Used in a conditional expression. If the number parameter is nonzero (or
if no number is supplied), this function sets a flag to terminate the
transformation.
Use the Terminate function to end the transformation if an event occurs.
This function does not roll back changes; it acts as if the transformation
has reached the source file. When a Terminate is reached, the
transformation is regarded as having been completed successfully and
changes are committed to the target.
To stop a transformation and roll back changes to the target, use the
Abort Function instead.
177
See Also
Abort Function, Discard Function, and Reject Function.
Example
The following function can be written in an AfterEveryRecord event to
terminate the transformation once all Account No records up to 10026
(tutor1.asc) are written.
If FieldAt("/SOURCE/R1/Account No") > 10026 Then
Terminate()
Else
FieldAt("/SOURCE/R1/Account No")
End If
TestMask Function
Description
Compares a string to a mask
Return
Boolean value
Return (Null)
Error: Incorrect argument count
Syntax
TestMask("string", "mask")
Parameters
This function has the following parameters:
Remarks
Name
Description
string (required)
Any valid string expression
that can be interpreted as a
numeric value. String may be
entered as a valid field name. If
a string literal, enclose in
quotation marks.
mask (required)
Any valid string expression
that represents display format
characters. The display format
characters describe how the
expression argument is to be
formatted. If a string literal,
enclose in quotation marks.
This function compares a string to a mask, and if it matches
exactly, it returns "–1" for a True result. Otherwise, it returns "0"
for a False result.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
178
Functions
See Also
ValMask Function
Example
Compare the string "$2,600" with the mask “$#,###”:
TestMask("$2,600", "$#,###")
Time, Time$ Functions
Description
Write current system time
Note: The Time and Time$ functions are interchangeable.
Return
Current system time
Return (Null)
Error: Incorrect argument count
Syntax
Time[$]( )
Parameters
None are required, however, parentheses are required to
follow the function name.
Remarks
Time returns a time stored as the fractional part of a doubleprecision number.
Time$ returns an eight-character string in the form of
hh:mm:ss, where hh is the hour (00 - 23), mm is the minute (00
- 59), and ss is the second (00 - 59). A 24-hour clock is used;
therefore, 6:00 P.M. displays as 18:00:00.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Date, Date$ Functions and Now Function
Example
This function returns the current system time:
Time()
TimeSerial Function
7
Description
Calculate time serial
Return
Time serial for a specific hour, minute, and second
Return (Null)
Error: Incorrect argument count
Syntax
TimeSerial(hour, minute, second)
Remarks
This function has the following parameters:
179
Parameters
Remarks
Name
Description
hour
An hour between 0 (12:00 AM)
and 23 (11:00 PM), inclusive,
or a numeric expression.
minute
A minute between 0 and 59,
inclusive, or a numeric
expression.
second
A second between 0 and 59,
inclusive, or a numeric
expression.
To express a specific time, such as 10:30:00, the range of
numbers for each TimeSerial parameter should conform to the
accepted range of values for this designation. These values are 0
through 23 for hours, and 0 through 59 for minutes and seconds.
Relative times for each parameter can also be specified by using
a numeric expression that represents the number of hours,
minutes, and seconds before or after a certain time, such as:
TimeSerial(12 - 1, 0 - 30, 0) for 10:30:00 AM. (Thirty minutes
before one hour before noon.)
TimeSerial returns a time stored internally as a double-precision
fractional number between 0 and .99999. This number
represents a time between 00:00:00 and 23:59:59, or 12:00:00
AM and 11:59:59 PM, inclusive.
If the time specified by the three parameters falls outside the
acceptable range of times, an error occurs.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Hour Function, Minute Function, Month Function, Now
Function, Second Function, TimeValue Function
Example
This example returns the time "10:30:00 AM". (one hour and 30
minutes before noon.):
TimeSerial(12 - 1, 0 - 30, 0)
TimeValue Function
180
Description
Find time value from a string argument
Return
Time represented by a string argument
Functions
Return (Null)
Error: Incorrect argument count
Syntax
TimeValue("strexpr")
Parameters
This function has the following parameters:
Remarks
Name
Description
"strexpr"
A string representing a time
from 00:00:00 (12:00:00 AM)
through 23:59:59 (11:59:59
PM). If a string literal, enclose
in quotation marks.
Valid times can be entered using a 12-hour or 24-hour clock. In
other words, both “5:30 PM” and “7:30:00” are valid arguments.
TimeValue returns a time stored internally as a double-precision
fractional number between 0 and .99999. This number
represents a time between 00:00:00 and 23:59:59, or 12:00:00
AM and 11:59:59 PM, inclusive.
If strexpr contains invalid date information, TimeValue returns
an error.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Hour Function, Minute Function, Month Function, Now
Function, Second Function, TimeSerial Function
Example
The following example prints the time string "2:30:25 PM" as
"14:30:25":
tval = TimeValue("2:30:25 PM")
print(Hour(tval) ,":", Minute(tval), ":",
Second(tval))
Transliterate Function
Description
Translate characters between two character sets
Return
Characters that meet the match criteria
Return (Null)
Error: Incorrect argument count
Syntax
Transliterate("source_char_set", "target_char_set", "string")
Parameters
This function has the following parameters:
181
Remarks
Name
Description
"source_char_set"
Defines the set of characters for the
source alphabet. Any character text
string. If a string literal, enclose in
quotation marks.
"target_char_set"
Defines the set of characters for the
target alphabet. Any character text
string. If a string literal, enclose in
quotation marks.
"string"
The character text string to be
transliterated. If a string literal,
enclose in quotation marks.
Transliterate converts characters in the third parameter string which are
members of the source alphabet to the corresponding characters in the target
alphabet.
If the source alphabet is larger than the target alphabet, the characters in the
source alphabet without corresponding elements in the target alphabet is
mapped to empty strings.
Caution: This function returns a value that must be used or stored to prevent
stack overflow. See Stack Overflow.
See Also
GSub Function, LTrim, LTrim$ Functions, StrReplace Function, Sub Function
Example
The following examples take the source and target character strings and return
a transliterated string:
Transliterate("abc", "ABC", "abcdefg")
Returns "ABCdefg"
Transliterate("abcdefg", "ABC", "abcdefg")
returns "ABC"
Transliterate(" ", "", "The red fox")
returns "Theredfox"
Transliterate("!@#$%", "______", "The national characters
!@#$%")
returns The national characters ____
182
Functions
Trim, Trim$ Functions
Description
Remove leading and trailing space from a string
Note: The Trim and Trim$ functions are interchangeable.
Return
Copy of a string with spaces removed from the beginning and end.
(Spaces in the middle of data will not be removed.)
Return (Null)
Error: Incorrect argument count
Syntax
Trim("stringexpr")
Parameters
This function has the following parameters:
Remarks
Name
Description
"stringexpr"
Any expression containing numeric
or text characters. If a string literal,
enclose in quotation marks.
The Trim Function is often used in conjunction with other functions.
Adding the Trim function is often the cure for otherwise nonworking
functions (such as when spaces occur in source data).
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
See Also
LTrim, LTrim$ Functions and RTrim, RTrim$ Functions
Example
The following example removes the spaces from the string " Test String ":
Trim(" Test String ")
Returns "Test String"
The following example removes the spaces from the data in ("FIELD1") so
the remainder of the expression will function correctly:
If(Trim("F/SOURCE/R1/IELD1") <> "",
DateValMask(FieldAt("/SOURCE/R1/FIELD1"), "yyyymmdd"),
"")
183
UBound Function
Description
Find the index of the last element (upper bound) in an array or an array
dimension
Return
Upper bound of the specified array
Return (Null)
Error: Invalid expression syntax
Syntax
UBound(ArrayName[, Dimension])
Parameters
This function has the following parameters:
Remarks
Name
Description
arrayname (required)
The array variable name.
dimension [optional]
Whole number indicating which
dimension's upper bound is returned.
(Use 1 for the first dimension, 2 for
the second, and 3 for the third. If
dimension is omitted, 1 is assumed.)
Each element of an array stores one value and is referenced by using its index
(coordinate position) after the array name. The index of the first element of an
array is called its lower bound. (See LBound Function.) The index of the last
element is called its upper bound. By default, an array is indexed beginning
with zero. The upper and lower bounds of an array can be inspected using
LBound and UBound.
Using scalar or undeclared variables results in a runtime error. Always declare
all variables before using UBound.
Caution: This function returns a value that must be used or stored to prevent
stack overflow. See Stack Overflow.
Example
Dim MyArray(1 To 100, 0 To 10, -5 To 5)
UBound(MyArray) (returns 100)
UBound(MyArray, 1) (returns 100)
UBound(MyArray, 2) (returns 10)
UBound(MyArray, 3) (returns 5)
184
Functions
UCase, UCase$ Functions
Description
Transform all characters in a string to uppercase
Note: The UCase and UCase$ functions are interchangeable.
Return
String with all uppercase characters
Return (Null)
Error: Incorrect argument count
Syntax
UCase[$]("strexpr")
Parameters
This function has the following parameters:
Name
Description
strexpr
Any string expression. If a string
literal, enclose in quotation marks.
Remarks
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
See Also
LCase, LCase$ Functions
Example
The following expression returns the string "REMAINS OF THE DAY":
UCase("Remains of the Day")
This expression causes the string data in ("Field 1") of the source data file
to be returned as uppercase in the target file.
UCase(FieldAt("/SOURCE/R1/Field 1"))
The expression below cleans data entered by various employees in the
source field ("FOOD TYPE"). The data includes many forms of the key word
"TEX" in all lower case, all upper case, mixed upper-lower, and a
combination of each. This expression changes the data to all uppercase,
extracts "TEX", and changes "TEX" to "TEX MEX". Any other data other
than "TEX" in the ("FOOD TYPE") field is converted to the target in its
original form, such as THAI or ITALIAN.
‘ When writing your own expression modeled upon the following
example, make sure the first line of your expression includes the entire
clause (from the word "If" through the word "Then").
If UCase(Left(Trim(FieldAt("/SOURCE/R1/FOOD TYPE") ),
3)) = "TEX" Then
"TEX MEX"
Else
UCase(Parse(1,Trim(FieldAt("/SOURCE/R1/FOOD TYPE")),
" "))
End If
185
UTF8Decode Function
Description
Decode UTF-8 formatted strings to be interpreted as Unicode
strings.
Return
Unicode format of the UTF-8 source string
Return (Null)
Error: Incorrect argument count
Syntax
UTF8Decode(src)
Parameters
This function has the following parameters:
Remarks
Name
Description
src (required)
The UTF-8 source string to
decode. You can specify a
name of a field. If a string
literal, enclose in quotation
marks.
UTF-8 is the Unicode transformation format that serializes a
Unicode scalar value as a sequence of one to four bytes.
In UTF-8, Unicode characters that correspond to the ASCII
character set are represented as the ASCII characters.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
B64Decode Function, B64Encode Function, and UTF8Encode
Function
Example
The following expression decodes the contents of "Field1":
UTF8Decode(FieldAt("/SOURCE/R1/Field1"))
UTF8Encode Function
186
Description
Encode Unicode strings to the UTF-8 format
Return
UTF-8 format of the Unicode source string
Return (Null)
Error: Incorrect argument count
Syntax
UTF8Encode(src)
Parameters
This function has the following parameters:
Functions
Remarks
Name
Description
src (required)
The Unicode source string to
encode. If a string literal,
enclose in quotation marks.
UTF-8 is the Unicode transformation format that serializes a
Unicode scalar value as a sequence of one to four bytes.
In UTF-8, Unicode characters that correspond to the ASCII
character set are represented as the ASCII characters.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
B64Decode Function, B64Encode Function, UTF8Decode
Function
Example
The following expression encodes the contents of "Field1" into
UTF-8 format:
UTF8Encode(FieldAt("/SOURCE/R1/Field1"))
Val Function
Description
Strip nonnumeric characters, blanks, tabs, and linefeeds from a
string
Return
Numeric value of a string of characters
Return (Null)
Error: Incorrect argument count
Syntax
Val(string)
Parameters
This function has the following parameters:
Name
Description
string
A sequence of characters that
can be interpreted as a
numeric value. If a string
literal, enclose in quotation
marks.
187
Remarks
This function stops reading the string at the first character (if it
does not recognize it as a number). Val also strips blanks, tabs,
and linefeeds from string.
Symbols and characters, such as dollar signs, commas, radix
prefixes, octal or hexadecimals are not recognized by Val as
numeric. Microsoft hexadecimal strings (i.e., Val("&H1A2B") are
recognized by Val as numeric.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
See Also
Format, Format$ Function and String, String$ Functions
Example
This expression returns 25 as a numeric value:
Val("25")
The following expression returns a numeric value for the data in
("FIELD1"), which is a "Text" data type in the source data file:
Val(FieldAt("/SOURCE/R1/FIELD1"))
ValMask Function
Description
Strip non-digit characters from a formatted string
Return
Numeric value from a formatted string
Return (Null)
Error: Incorrect argument count
Syntax
ValMask(string, mask)
Remarks
ValMask strips out nondigit characters and converts the result to
a valid numeric value. Characters that ValMask will strip include:
$, % e
TestMask is similar to ValMask, but returns True if the string
matches the mask and False if the string does not match exactly.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
Parameters
This function has the following parameters:
Name
188
Description
Functions
string
Any valid string expression
that can be interpreted as a
numeric value. String may be
entered as a valid field name. If
a string literal, enclose in
quotation marks.
mask
Any valid string expression
that represents display format
characters. The display format
characters describe how the
expression argument is to be
formatted. If a string literal,
enclose in quotation marks.
See Also
DateValMask Function, Val Function, StrReplace Function
Example
The following expression returns a numeric value for the data in
("FIELD1"), which is a "Text" data type, but contains numbers
such as 123.50 in the source data file. It changes $2,600 to 2600:
ValMask("$2,600", "$#,###")
This example performs many tasks on the source field ("Field1").
The StrReplace function strips out commas, moves negative
signs to the front of strings, and removes decimal points and
commas. Next, the ValMask function converts the text strings to
numeric strings:
a = StrReplace(",", "", StrReplace(".", "",
FieldAt("/SOURCE/R1/Field1") ))
IIf (Right(FieldAt("/SOURCE/R1/Field1") ,1) = "", (ValMask(FieldAt("/SOURCE/R1/
Field1"),"###############")*-1),Val( a ))
Weekday Function
Description
Return an integer that represents the day of the week for a
specified date string
Return
Integer between 1 and 7
Return (Null)
Error: Incorrect argument count
Syntax
Weekday(number)
189
Parameters
Remarks
This function has the following parameters:
Name
Description
number
Any numeric expression that
can represent a date and/or
time from January 1, 100
through December 31, 9999,
where January 1, 1900 is 2.
Numbers to the left of the decimal point in number represent
the date; numbers to the right of the decimal point represent
the time. Negative numbers represent dates prior to December
30, 1899.
If number is null, Weekday returns a null.
Caution: This function returns a value that must be used or
stored to prevent stack overflow. See Stack Overflow.
The following are the days of the week and the corresponding
integer that is returned with this function:
See Also
190
Weekday
Integer
Sunday
1
Monday
2
Tuesday
3
Wednesday
4
Thursday
5
Friday
6
Saturday
7
DatePart Function, Day Function, Hour Function, Minute
Function, Month Function, Now Function, Second Function,
Year Function
Functions
Example
This expression returns an integer relating to the current system
date. For example, Field1 contains the date 12/01/2003. This
date was a Monday, so a "2" will returned to the target:
Weekday(FieldAt("/SOURCE/R1/Field1"))
In this example, a date is assigned as "MyAnniversary". A "4" is
returned to the target, since November 13, 2002 was a
Wednesday:
MyAnniversary = "November 13, 2002"
Weekday(MyAnniversary)
Xlate Function
Description
Look for specific data in a field in the source file, and replace that data in
the target file with values from an external table.
Return
Values, including strings, hex values, and decimal values from a two
column table
Return (Null)
Error: Incorrect argument count
Syntax
Xlate("string", "table")
Remarks
Xlate allows "lookups" on decimal values (0-255), strings (single
characters), and hex values. Decimal values are the recommended table
element.
To use the Xlate function, create and save a lookup table in a simple text
editor. The table must contain two columns of data. Each line in the
lookup table must contain a lookup key in one column, a separator (must
be a space or a tab), and a corresponding value in the second column.
Caution: This function returns a value that must be used or stored to
prevent stack overflow. See Stack Overflow.
Parameters
The parameters of this function are:
Name
Description
191
string
The string to search for. If a string literal,
enclose in quotation marks. See the table
below for details on how to enter the three
different types of strings.
When you create the lookup table, you must
enter the elements of the table as follows:
table
The lookup table file name (including drive and
path if it is not in your Common directory). If a
string literal, enclose in quotation marks.
Element
Description
Decimal values
Enter as a value
between 0 and 255.
Example: 112
080
Strings
Enter the literal string
enclosed in single
quotes.
Example: ‘p’
‘P’
Hex values
Enter a 0, an X, and
then the two digit hex
value.
Example: 0x70
0x50
See Also
GSub Function, Sub Function, LTrim, LTrim$ Functions, StrReplace
Function, Transliterate Function
Example
In this example, the map looks for any key in the lookup table file
"filename.txt", and for any found key in ("Field1") of the source file. Then
it will write the corresponding value(s) in the current field for every
record in the target file:
Xlate(Fields("/SOURCE/R1/Field1"), "filename.txt")
192
Functions
Year Function
Description
Extract the year numeric value from any numeric string that represents a date
Return
Integer between 100 and 9999, inclusive, which represents the year of a date
argument
Return (Null)
Error: Incorrect argument count
Syntax
Year(number)
Parameters
This function has the following parameters:
Remarks
Name
Description
number
Any numeric expression that can
represent a date and/or time from
January 1, 100 through December 31,
9999, where January 1, 1900 is 2.
Numbers to the left of the decimal point in number represent the date;
numbers to the right of the decimal point represent the time. Negative numbers
represent dates prior to December 30, 1899.
If number is null, Year returns a null.
Caution: This function returns a value that must be used or stored to prevent
stack overflow. See Stack Overflow.
See Also
DatePart Function, Day Function, Hour Function, Minute Function, Month
Function, Now Function, Second Function, Weekday Function
Example
This example returns the current system year plus 30 years:
Year(FieldAt("/SOURCE/R1/DATE")+30)
This example returns the year portion from dates in the source ("ShipDate").
The DateValue function defines each date as date values, while the Year
function defines those values as years:
a = DateValue(Trim(FieldAt("/SOURCE/R1/ShipDate")))Year(a)
193
194
Operators
Operators
Scripting operators fall into categories. To learn more about each type of operator, click the
corresponding link:
•
•
•
•
•
•
Recognition Rule Operators
Arithmetic Operators
Assignment Operator
Comparison Operators
Concatenation Operator
Logical Operators
Recognition Rule Operators
When defining a recognition rule, you need to select an operator for an implied expression
that begins with the discriminator field.
= Operator
<> Operator
< Operator
<= Operator
> Operator
>= Operator
Any Value Operator
This operator type acts like an Else statement. In other words, if the rule compares all the
discriminators and the record does not match any of them, it matches the Any Value
operator. Use this operator as the last rule to catch values that do not match any other
records. If you do not have this kind of default, the first record defined is used.
Between Operator
The Between operator matches records that are between the low value and high value set
when defining a recognition rule. The match is true if the value is greater than the low
value, and less than the high value.
~ Operator
!~ Operator
195
Like Operator
The Like operator in the record recognition rules is the SQL Like operator (with the addition
of '#').
% - matches any string of zero or more characters
_ - matches any single character
# - matches any single digit (this is an extension to the SQL Like operator)
This operator cannot be included in any of the other more specific categories, but it is very
useful and deserves documentation.
The Like operator is especially useful when you are attempting to write Record
Expressions. For example, assume you have a ("State") field in your source file that is a 5
byte field and contains the "official" two digit abbreviations for states in the United States.
You only want to convert those records for the state of Montana (abbreviated MT). Since
the ("State") field actually contains two letters and three spaces, you should use the Like
operator (instead of the = operator) so a map looks for the letters "MT" anywhere within
those 5 bytes of the field. In the Record Expressions area of the Filter Windows, the
expression would be written as follows:
FieldAt("/SOURCE/R1/State") Like "MT"
With the Like operator, there are a few special characters that you can use to look for a
pattern rather than a literal string. They have different meanings from the same characters
in other contexts:
? - indicates any one single character (like "." in other contexts)
* - indicates 0 or more characters (like ".*" in other contexts)
# - indicates a digit (like "[0-9]" in other contexts).
[and] - character classes are interpreted the same as in other contexts
With the Like operator, the entire string excluding leading and trailing spaces must match
the regular expression.
See Also
Regular Expressions
Regular Expression Operator
A regular expression operator is a string of characters that defines a set of rules for
matching character strings found in fields.
196
Operators
See Also
Search for “discriminator field” in the documentation.
Regular Expressions
Arithmetic Operators
Arithmetic operators are used to perform calculations on numeric data in a field or fields.
They may be used alone or in combination with other operators and functions in both
target field expressions.
• Numeric operands are promoted to double precision values before performing the
operation.
• If both operands are integer values and the result can be represented as an integer,
the operator returns an integer value.
• If one or both operands are Null, then the result is Null. All other values are treated as
a numeric value of zero.
Arithmetic Operator Symbol
Name
+
addition
-
subtraction
*
multiplication
/
division
\
division of integers
^
exponentiation
mod
mod
& string concatenation
concatenate
It is important to understand that calculations cannot be performed on data that contains
nonnumeric characters, or is defined as Text data type. However, there are functions
available that allow you to convert data from Text to numeric values. See Val Function and
ValMask Function.
197
Task
Description
Expression
Multiply the contents of
two fields from the
source file
Source field names are
Quantity and Price.
Target field name is
TOTAL SALE.
TOTAL SALE=FieldAt("/SOURCE/R1/
Quantity")*("Price")
Multiply the contents of
one field from the source
file by a literal value (add
7.25% sales tax)
Source field name is
Total. Target field name is
GRAND TOTAL.
GRAND TOTAL= FieldAt("/SOURCE/R1/
Total") * 1.0725
Divide the contents of
one field by the contents
of another field from the
source file
Source field names are
Total and Quantity.
Target field name is
PRICE PER.
PRICE PER= FieldAt("/SOURCE/R1/Total
Sale") / FieldAt("/SOURCE/R1/
Quantity")
Add the contents of two Source field names are
fields from the source file Total and Tax. Target field
name is GRAND TOTAL.
GRAND TOTAL= FieldAt("/SOURCE/R1/
Total") + FieldAt("/SOURCE/R1/Tax")
* Operator
Description
Multiply two numeric operands
Syntax
result = operand1 * operand2
Remarks
Numeric operands are promoted to double precision values
before being multiplied. If both operands are integer values and
the result can be represented as an integer, then the operator
returns an integer value.
If one or both operands are Null, then the result is Null. All other
values are treated as a numeric value of zero.
Example
The following expression returns the value of the contents of the
field Salary multiplied by the constant 2.
FieldAt("/SOURCE/R1/Salary") * 2
This expression returns the value of the contents of the Price Per
field multiplied by the contents of the Quantity field:
FieldAt("/SOURCE/R1/Price Per") * FieldAt("/
SOURCE/R1/Quantity")
See Also
198
+ Operator, - Operator, / Operator, \ Operator, ^ Operator, =
Operator, <= Operator, <> Operator, < Operator, >= Operator, >
Operator, and Mod Operator
Operators
+ Operator
Description
Add two numeric operands or concatenates two string operands
Syntax
result = operand1 + operand2
Remarks
The + operator treats operands as numbers (unless both are
dates, and one contains only time information). So if either or
both is a string, it is treated as a number. For string
concatenation, the & operator is preferred to the + operator
because there is less ambiguity.
Numeric operands are promoted to double precision values
before being added. If both operands are integer values and the
result can be represented as an integer, then the operator
returns an integer value.
If one or both operands are Null, then the result is Null.
Example
The following expression adds the contents of two numeric
fields, Bonus and Salary:
FieldAt("/SOURCE/R1/Bonus") + FieldAt("/SOURCE/
R1/Salary")
The following expression adds a constant value to the value in an
existing field.
FieldAt("/SOURCE/R1/Field10") + 100
For more information, see Arithmetic Operators.
See Also
& Operator, * Operator, - Operator, / Operator, \ Operator, ^
Operator, = Operator, <= Operator, <> Operator, < Operator, >=
Operator, > Operator, and Mod Operator
- Operator
Description
Find the difference between two numeric operands or change
the sign of a numeric operand
Syntax
Syntax 1: result = operand1 - operand2
Syntax 2: result = - operand
199
Remarks
The first form of the operator (Syntax 1) calculates the difference
between two numeric values. It is the subtraction operator. In
the second form (Syntax 2), the operator is arithmetic negation
operator.
Numeric operands are promoted to double precision values
before performing the operation. If both operands are integer
values and the result can be represented as an integer, then the
operator returns an integer value.
If one or both operands are Null, then the result is Null. All other
values are treated as a numeric value of zero.
Example
The following expression calculates the difference between two
numeric fields List Price and Price:
FieldAt("/SOURCE/R1/List Price") – FieldAt("/
SOURCE/R1/Price"
The following expression calculates the difference between a
numeric field and a constant.
FieldAt("/SOURCE/R1/List Price") - 20
See Also
& Operator, * Operator, + Operator, / Operator, \ Operator, ^
Operator, = Operator, <= Operator, <> Operator, < Operator, >=
Operator, > Operator, and Mod Operator
\ Operator
Description
Integer division operator. Divide two numbers and return the
integer result.
Syntax
result = operand1 \ operand2
Remarks
If one or both operands are Null, then the result is Null. All other
nonnumeric values (empty strings, strings composed of letters)
are treated as a numeric value of zero
Example
The following example determines if the field Quantity contains
an even number
(FieldAt("/SOURCE/R1/Quantity") * (FieldAt("/
SOURCE/R1/Quantity")\2))
See Also
200
& Operator, * Operator, + Operator, - Operator, / Operator, ^
Operator, = Operator, <= Operator, <> Operator, < Operator, >=
Operator, > Operator, and Mod Operator
Operators
/ Operator
Description
Division operator. Divide two numbers and return a result.
Syntax
result = operand1 / operand2
Remarks
Numeric operands are promoted to double precision values
before performing the operation. If both operands are integer
values and the result can be represented as an integer, then the
operator returns an integer value.
If one or both operands are Null, then the result is Null. All other
nonnumeric values (empty strings, strings composed of letters)
are treated as a numeric value of zero.
Example
The following example calculates the average monthly sales by
dividing the contents of the Annual Sales field by the constant
value of 12:
FieldAt("/SOURCE/R1/Annual Sales") / 12
The following expression divides the numeric contents of one
field by the numeric contents of another field:
FieldAt("/SOURCE/R1/Field10") / FieldAt("/
SOURCE/R1/Field23")
See Also
& Operator, * Operator, + Operator, - Operator, / Operator, ^
Operator, = Operator, <= Operator, <> Operator, < Operator, >=
Operator, > Operator, and Mod Operator
^ Operator
Description
Raise a number to the power of an exponent
Syntax
result = number ^ exponent
Remarks
Numeric operands are promoted to double precision values
before performing the operation. If both operands are integer
values and the result can be represented as an integer, then the
operator returns an integer value.
If one or both operands are Null, then the result is Null. All other
values are treated as a numeric value of zero.
201
Example
The following expression returns the value of the field Distance
squared:
FieldAt("/SOURCE/R1/Distance")^2
See Also
& Operator, * Operator, + Operator, - Operator, / Operator, \
Operator, = Operator, <= Operator, <> Operator, < Operator, >=
Operator, > Operator, and Mod Operator
Mod Operator
Description
Divide two numbers and returns only the remainder
Syntax
result = operand1 Mod operand2
Remarks
Mod is a shortened term for modulus. Mod divides operand1 by
operand2 (rounding floating-point numbers to integers) and
returns only the remainder as result. The operands can be any
numeric expression.
The data type of result is usually an Integer or a Long. However,
result is a Null if one or both of the operands are Null
expressions. Any operand that is Empty is treated as 0 (zero).
Example operators,
arithmetic:
This example divides 200000 by 9 and determines the
remainder. It returns 2.
200000 Mod 9
Mod is calculated as follows:
I - n * (I \ n)
Where:
I is a counter
n is the field count
"\" divides integers
See Also
202
& Operator, * Operator, + Operator, - Operator, / Operator, \
Operator, ^ Operator, = Operator, <= Operator, <> Operator, <
Operator, >= Operator, and > Operator
Operator
Calculation
Result
1 Mod 12
1 - 12 * (1 \ 12)
1
2 Mod 12
2 - 12 * (2 \ 12)
2
Operators
3 Mod 12
3 - 12 * (3 \ 12)
3
4 Mod 12
4 - 12 * (4 \ 12)
4
5 Mod 12
5 - 12 * (5 \ 12)
5
6 Mod 12
6 - 12 * (6 \ 12)
6
7 Mod 12
7 - 12 * (7 \ 12)
7
8 Mod 12
8 - 12 * (8 \ 12)
8
9 Mod 12
9 - 12 * (9 \ 12)
9
10 Mod 12
10 - 12 * (10 \ 12)
10
11 Mod 12
11 - 12 * (11 \ 12)
11
12 Mod 12
12 - 12 * (12 \ 12)
0
Test your Mod operator calculations before running a transformation by opening the
Windows Calculator and selecting Scientific mode. Using the examples above, click on "1",
then "Mod", then "12". The result is "1".
Assignment Operator
An assignment operator assigns the value of the right operand to the left operand. That is,
x = y assigns the value of y to x.
Assignment and Comparison operators may be confusing. For instance, the = Operator is
not a Comparison operator. It is an Assignment operator.
For comparisons of x and y, use the == Operator.
= Operator
Description
Assign the value of the right operand to the left operand
Syntax
operand1 = operand2
Remarks
The = operator is NOT a Comparison operator. It is an
ASSIGNMENT operator. For comparisons of x and y, use the ==
Operator.
203
Example
The following assigns 0 (zero) to the contents of the ("Items")
field.
FieldAt("/SOURCE/R1/Items")= 0
See Also
== Operator and Comparison Operators
Tip The = operator is an ASSIGNMENT operator. Do not confuse it with the == operator,
which is a COMPARISON operator. When you want to compare fields and values, use the
== Operator.
Comparison Operators
Comparison operators compare the contents in a field to either the contents in another
field or a constant. They may be used alone or in combination with other operators and
functions in both record expressions and target field expressions.
The Comparison operators are:
< Operator
> Operator
<= Operator
>= Operator
!~ Operator
== Operator
<> Operator
~ Operator
204
Comparison Operator Symbol
Name
==
compares operands
<>
not equal to
<
less than
>
greater than
<=
less than or equal to
>=
greater than or equal to
Operators
Comparison Operator Symbol
Name
!~
does not contain
~
string comparison
like
like
Filter Expression Examples
To select only the records in which the quantity field in the source file is a numeric value
of less than or equal to 1000, write this expression:
1000 <= FieldAt("/SOURCE/R1/Quantity")
To select only the records in which the quantity field in the source file is a numeric value
greater than 1000, write this expression:
1000 > FieldAt("/SOURCE/R1/Quantity")
To select only the records in which the ordered field in the source file contains values not
equal to the values in the shipped field, write this expression:
FieldAt("/SOURCE/R1/Ordered") <> FieldAt("/SOURCE/R1/Shipped")
To select only the records in which the Address field contains "P.O. Box" with or without
capitol letters, periods, or spaces, write this expression. This will convert all records for
people who have postal box addresses.
FieldAt("/SOURCE/R1/Address") ~ "[Pp]\.*[Oo]\.* *[Bb][Oo][Xx]"
To select only the records in which the ZIP field does not contain a five-digit number, write
this expression. This will only convert records that are missing a zip code.
FieldAt("/SOURCE/R1/ZIP")!~ "[0-9][0-9][0-9][0-9][0-9][-][0-9][09][0-9][0-9]"
To select only the records in which the size field in the source file is exactly "10mm", write
this expression:
FieldAt("/SOURCE/R1/Size")=="10mm"
To select only the records in which the quantity field in the source file is a text field and
must be exactly 1000, write this expression:
Val(FieldAt("/SOURCE/R1/Quantity"))==1000
205
< Operator
Description
Compare two operands to determine if the first operand is less
than the second operand
Syntax
result = operand1 < operand2
Remarks
The result of a comparison is True or False. The following rules
are used to determine how the operands are compared.
• If both operands are numeric, then a numeric comparison is
performed.
• If either of the operands is a string value, then a string
comparison is used.
• If either operand is Null, then the result is Null.
Example
The following determines if the contents of the Salary field are
less than 75000:
FieldAt("/SOURCE/R1/Salary") < 75000
See Also
& Operator, * Operator, + Operator, - Operator, / Operator, \
Operator, ^ Operator, = Operator, <= Operator, <> Operator, <
Operator, >= Operator, > Operator, Mod Operator, and
Comparison Operators
> Operator
Description
Compare two operands to determine if the first operand is
greater than the second operand
Syntax
result = operand1 > operand2
Remarks
The result of a comparison is always True, False, or Null. The
following rules are used to determine how the operands are
compared.
• If both operands are numeric, then a numeric comparison is
performed.
• If either of the operands is a string value, then a string
comparison is used.
• If one or both operands are Null, then the result is Null.
206
Operators
Example
The following determines if the contents of the Salary field are
greater than 75000:
FieldAt("/SOURCE/R1/Salary") > 75000
See Also
& Operator, * Operator, + Operator, - Operator, / Operator, \
Operator, ^ Operator, = Operator, <= Operator, <> Operator, <
Operator, >= Operator, > Operator, Mod Operator, and
Comparison Operators
<= Operator
Description
Compare two operands to determine if the first operand is less
than or equal to the second operand
Syntax
result = operand1 <= operand2
Remarks
The result of a comparison is always True, False, or Null. The
following rules are used to determine how the operands are
compared.
• If both operands are numeric, then a numeric comparison is
performed.
• If either of the operands is a string value, then a string
comparison is used.
• If one or both operands are Null, then the result is Null.
Example
The following determines if the contents of the Salary field are
less than or equal to 75000.
FieldAt("/SOURCE/R1/Salary") <= 75000
See Also
& Operator, * Operator, + Operator, - Operator, / Operator, \
Operator, ^ Operator, = Operator, <= Operator, <> Operator, <
Operator, >= Operator, > Operator, Mod Operator, and
Comparison Operators
>= Operator
Description
Compare two operands to determine if the first operand is
greater than or equal to the second operand
Syntax
result = operand1 >= operand2
207
Remarks
The result of a comparison is always True, False, or Null. The
following rules are used to determine how the operands are
compared.
• If both operands are numeric, then a numeric comparison is
performed.
• If either of the operands is a string value, then a string
comparison is used.
• If one or both operands are Null, then the result is Null.
Example
The following determines if the contents of the Quantity field
are greater than or equal to 5.
FieldAt("/SOURCE/R1/Quantity")>=5
See Also
& Operator, * Operator, + Operator, - Operator, / Operator, \
Operator, ^ Operator, = Operator, <= Operator, <> Operator, <
Operator, >= Operator, > Operator, Mod Operator, and
Comparison Operators
!~ Operator
Description
Compare a string with a regular expression pattern to see if the
pattern is NOT contained somewhere in the string
Syntax
result = string !~ "pattern"
Remarks
The result of a contains comparison is always True or False. If the
pattern is found, a False is returned. If not, True.
The advantage of this operator is that you can search for a
particular string or pattern of data in a large field. If that string
or pattern does not exist anywhere in the field, then some action
can be taken on the whole field. Also, the option of matching a
pattern, not necessarily a literal string, makes the matching
capabilities far more flexible.
This operator requires a regular expression as the pattern. It
recognizes all special characters. For information on regular
expressions and special characters, see Regular Expressions.
If either operand is Null, then the result is Null.
208
Operators
Example
The regular expression ".y.*" means any string containing any
character followed by 'y' followed by any number of characters.
This expression tests to see if that pattern exists in the string.
If "Big test string" !~ ".y.*" Then
LogMessage("It's not in there.")
Else
LogMessage("It's in there.")
End if
This expression converts any record where Field7 does not
contain the letters "CR" anywhere in it.
FieldAt("/SOURCE/R1/Field7") !~ "CR"
See Also
& Operator, * Operator, + Operator, - Operator, / Operator, \
Operator, ^ Operator, = Operator, <= Operator, <> Operator, <
Operator, >= Operator, > Operator, Mod Operator, and
Comparison Operators
== Operator
Description
Compare operands and returns a Boolean value based upon
whether the comparison is True or not. The operands may be
numerical or string values.
Syntax
operand1 == operand2
Remarks
The result of this comparison operator is a Boolean value of
True, or False. True returns a value of "-1", while False returns
"0".
The following rules are used to determine how the operands are
compared:
• If both operands are numeric, then a numeric comparison is
performed.
• If either of the operands is a string value, then a string
comparison is used. Enclose strings in quotes ("string").
209
Example
To compare the contents of the "Account No" field and find each
instance of the string "10024", use the following:
FieldAt("/SOURCE/R1/Account No")=="10024"
See Also
& Operator, * Operator, + Operator, - Operator, / Operator, \
Operator, ^ Operator, = Operator, <= Operator, <> Operator, <
Operator, >= Operator, > Operator, Mod Operator, and
Comparison Operators
Tip The == operator is a COMPARISON operator. Do not confuse it with the = operator,
which is an ASSIGNMENT operator. When you want to assign a value, use the = Operator.
If the operator is the second token in a statement and the first token is a variable name, it
is interpreted as an assignment. Do not confuse the = operator with this operator. In this
instance, if you use the = instead of ==, all "Account No" fields return empty (instead of
with Boolean values).
<> Operator
Description
Compares two operands to determine if the first operand is not
equal to the second operand.
Syntax
result = operand1 <> operand2
Remarks
The result of a comparison is always True, False, or Null. The
following rules are used to determine how the operands are
compared.
• If both operands are numeric, then a numeric comparison is
performed.
• If either of the operands is a string value, then a string
comparison is used.
If one or both operands are Null, then the result is Null.
Example
The following determines if the contents of the Items Ordered
field is different than the contents of the Items Shipped field:
FieldAt("/SOURCE/R1/Items Ordered")<>FieldAt("/
SOURCE/R1/Items Shipped")
See Also
210
& Operator, * Operator, + Operator, - Operator, / Operator, \
Operator, ^ Operator, = Operator, <= Operator, <> Operator, <
Operator, >= Operator, > Operator, Mod Operator, and
Comparison Operators
Operators
Concatenation Operator
Use a concatenation operator to concatenate or merge data from two or more fields in the
source file into a single field in the target file.
Note The + operator should not be used to concatenate strings because of potential
ambiguities resulting from its use for addition.
Examples
To Concatenate two fields from the source file, with a space between the data in the target
file source field names are ("First Name") and ("Last Name"). Write this target field
expression:
FieldAt("/SOURCE/R1/First Name") & " " & FieldAt("/SOURCE/R1/Last
Name")
To concatenate three source file fields, with a comma and a space between two of the
fields and two spaces between the other two fields. Source field names are: ("City")
("State") ("ZIP"). Write this target field expression:
FieldAt("/SOURCE/R1/City") & "," & FieldAt("/SOURCE/R1/State") & "
" & FieldAt("/SOURCE/R1/ZIP")
& Operator
Description
Concatenate two operands after coercing each operand to a
string value
Syntax
result = operand1 & operand2
Remarks
The & operator creates a string result from its two operands.
Numeric operands are first converted to string values. Null
valued operands are treated as empty strings except in the case
where both operands are Null. If both operands are Null, then
the result of the operation is also Null.
211
Example
The following example uses the & operator to concatenate the
contents of two fields with no space between the data.
FieldAt("/SOURCE/R1/Field12") & FieldAt("/
SOURCE/R1/Field30")
The following example uses the & operator to concatenate the
contents of three fields with a space between each piece of the
data:
FieldAt("/SOURCE/R1/First Name") & " " &
FieldAt("/SOURCE/R1/Middle Initial") & " " &
FieldAt("/SOURCE/R1/Last Name")
The following example uses the & operator to concatenate a
string of data to the end of the data in an existing field with a
space between each piece of the data.
FieldAt("/SOURCE/R1/Field2") & " " & FieldAt("/
SOURCE/R1/REGION")
The following example takes a 10-digit phone number from the
("Phone_Number") source field and converts it to a standard
phone number format with dashes (such as 512-459-1308).
Left(FieldAt("/SOURCE/R1/Phone_Number"), 3) & "" & Mid(FieldAt("/SOURCE/R1/Phone_Number"), 4,3)
& "-" & Right(FieldAt("/SOURCE/R1/
Phone_Number"),4)
See Also
* Operator, + Operator, - Operator, / Operator, \ Operator, ^
Operator, = Operator, <= Operator, <> Operator, < Operator, >=
Operator, > Operator, and Mod Operator
Logical Operators
Logical operators evaluate conditions. Use logical operators to specify multiple criteria in
an expression. For example, use them in record filtering expressions when you want to
select particular records based on information from two or more fields.
Examples
To select only records where ("Start Date") equals 01/01/94 and where ("End Date") equals
01/31/94 (within the same record). The And operator usually yields fewer records than the
Or operator. The DateValue function is used to convert text strings to dates. Write:
FieldAt("/SOURCE/R1/Start Date")=DateValue(01/01/94) And
FieldAt("/SOURCE/R1/End Date")=DateValue(01/31/94)
To select records when the ("Start Date") and ("End Date") fields are 'Text' or 'Character'
data, enclose dates in quotation marks. The DateValue function is not necessary. Write:
212
Operators
FieldAt("/SOURCE/R1/Start Date") = "01/01/94" And FieldAt("/SOURCE/
R1/End Date") = "01/31/94"
To select records where either the first or the second criteria is met. Select records where
the ("Start Date") field contains 01/01/94, regardless of the ("End Date"), and all records
where the ("End Date") field contains 01/31/94, regardless of the ("Start Date"). The Or
operator usually yields more records than the And operator. Write:
FieldAt("/SOURCE/R1/Start Date") = DateValue(01/01/94) Or
FieldAt("/SOURCE/R1/End Date") = DateValue(01/31/94)
To select records where the ("DateofBirth") field is not blank, write:
Not IsNull(FieldAt("/SOURCE/R1/DateofBirth"))
And Operator
Description
Logical conjunction of two operands
Syntax
result = operand1 And operand2
Remarks
The And operator determines the logical conjunction of the two
operands by treating nonzero values as a value of True and zero
values as False.
Example
The following expression evaluates to True if the contents of
field Salary are greater than 50000 and the field HomeOwner is
false.
FieldAt("/SOURCE/R1/Salary") > 50000 And Not
FieldAt("/SOURCE/R1/HomeOwner")
See Also
Or Operator and Or Operator
The following truth table shows how different combinations of operands are evaluated.
operand1
operand2
result
True (nonzero)
True
True
True
False (0)
False
True
Null
Null
False
True
False
False
False
False
False
Null
False
213
operand1
operand2
result
Null
True
Null
Null
False
False
Null
Null
Null
~ Operator
Description
Compare a string with a regular expression pattern to see if the
pattern is contained somewhere in the string
Syntax
result = string ~ "pattern"
Remarks
The result of a contains comparison is always True or False. If the
pattern is found, a True is returned. If not, False.
The advantage of this operator is that you can search for a
particular string or pattern of data in a large field. If that string
or pattern exists anywhere in the field, then some action can be
taken on the whole field. Also, the option of matching a pattern,
not necessarily a literal string, makes the matching capabilities
far more flexible.
This operator requires a regular expression as the pattern. It
recognizes all special characters. For information on regular
expressions and special characters, see Regular Expressions.
If either operand is Null, the result is Null.
Example
The regular expression ".y.*" means any string containing any
character followed by 'y' followed by any number of characters.
This expression will test to see if that pattern exists in the string.
If "abcxyzzy" ~ ".y.*" Then
LogMessage("It's in there.")
Else
LogMessage("It's not in there.")
End if
This expression converts any record where the Field7 contains
the letter X somewhere in it.
FieldAt("/SOURCE/R1/Field7") ~ "X"
See Also
214
Arithmetic Operators and Comparison Operators
Operators
Or Operator
Description
Perform a logical disjunction on two expressions
Syntax
result = expr1 Or expr2
Remarks
If either or both expressions evaluate True (nonzero), result is
True (-1). To see how result is determined, see the Truth table
following this table.
Example
This expression evaluates both the ("Total Cost") field and the
("Zone") field. When using the Or operator, either condition can
be true to return "Yes" to the target. If both criteria are false,
then "No" is returned. The Trim Function is used to trim any
leading or trailing spaces. The Val Function converts text data
types into numeric values before mathematical evaluations are
performed. See Trim, Trim$ Functions and Val Function.
If Trim(Val(FieldAt("/SOURCE/R1/Total Cost"))
>100000) Or Trim(FieldAt("/SOURCE/R1/Zone") Like
"SW") Then
"Yes"
Else
"No"
End If
See Also
And Operator and Not Operator
If expr1 is
And expr2 is
result is
True (nonzero)
True
True (-1)
True
False (0)
True
True
Null
True
False
True
True
False
False
False (0)
False
Null
Null
Null
True
True
215
If expr1 is
And expr2 is
result is
Null
False
Null
Null
Null
Null
The Or operator also performs a bit-wise comparison of identically positioned bits in two
numeric expressions and sets the corresponding bit in result according to the following
table:
If bit in expr1 is
And bit in expr2 is
result is
0
0
0
0
1
1
1
0
1
1
1
1
Not Operator
Description
Negate a numeric expression
Syntax
result = Not expr
Remarks
The Not operator inverts the bit values of any variable. If an
integer variable has the value 0 (False), the variable becomes -1
(True); if it has the value of -1, it becomes 0.
Example
This example uses the Not operator to determine whether the
value 1000 occurs in the source ("Field1").
Not(FieldAt("/SOURCE/R1/Field1") = 1000)
See Also
216
Like Operator
If expr is
Then result is
True (nonzero)
False (0)
False (0)
True (-1)
Null
Null
Operators
The Not operator performs a bit-wise comparison of identically positioned bits in two
numeric expressions and sets the corresponding bit in result according to the following
table.
Bits in expr
Bit in result
0 (zero)
1
1
0 (zero)
Like Operator
Description
Compare two string expressions
Syntax
result = expression Like pattern
Remarks
If expression matches pattern, result is True (-1); if there is no
match, result is False (0); and if either expression or pattern is a
Null, result is also a Null. The default string-comparison method
is Binary.
Built-in pattern matching provides a versatile tool for string
comparisons. The pattern-matching features allow you to use
wildcard characters, like those recognized by the operating
system, to match strings. For the wildcard characters you can
use and the number of digits or strings they match, see the table
following this one.
Example
This illustrates how Like is used in an expression when the data
you want to match in a particular field does not occupy the
entire field. In this case, the "Equal to" (==) comparison operator
does not produce the results you expect, so use the Like
operator as follows:
("FIELD1") Like "No*"
See Also
== Operator, ~ Operator,!~ Operator, Regular Expressions, and
Comparison Operators
Characters in Pattern
Matches in Expressions
?
Any single character
*
Zero or more characters
#
Any single digit (0 - 9)
217
Characters in Pattern
Matches in Expressions
[charlist]
Any single character in charlist
[^charlist]
Any single character not in charlist
word1|word2|word3
Any of the words on each side of line
(|)
A group of one or more characters (charlist) enclosed in brackets ([ ]) can be used to match
any single character in expression and can include almost any characters in the ANSI
character set, including digits. In fact, the special characters left bracket ([ ), question mark
(?), number sign (#), and asterisk (*) can be used to match themselves directly only by
enclosing them in brackets. The right bracket ( ]) cannot be used within a group to match
itself, but it can be used outside a group as an individual character.
In addition to a simple list of characters enclosed in brackets, charlist can specify a range
of characters by using a hyphen (-) to separate the upper and lower bounds of the range.
For example, [A - Z] in pattern results in a match if the corresponding character position in
expression contains any of the uppercase letters in the range A through Z. Multiple ranges
are included within the brackets without any delimiting. For example, [a - zA - Z0 - 9]
matches any alphanumeric character.
The pipe (|) has special meaning when used with the Like operator. It can be used to
provide two or more alternative strings to match against expression. All the strings except
for the last are used to match the start of a string. The text after the last pipe is used to
match the end of the string. For example, "yes|no|maybe" matches strings that have "yes"
or "no" at the start and/or "maybe" at the end.
Like Operator Notes
The Like operator requires an entire string, rather than just a portion, to match the regular
expression.
Example
‘The following example matches "abc", "bbbbbb", "ccc" and "cababc".
~ "[abc]{3}"
‘The following example matches "abc" and "ccc", but not "bbbbbb" or
"cababc".
Like "[abc]{3}"
218
Operators
Tip Regular expressions can also be used in SQL actions. However, it is important to note
that the syntax and special characters used in these depends on the connector database.
Refer to your database application documentation for details.
Important Pattern Matching Rules
• The caret character (^) at the beginning of charlist means that a match is made if any
character except those in charlist are found in expression. When used outside
brackets, the caret matches itself.
• The hyphen (-) can appear either at the beginning (after a caret if one is used) or at the
end of charlist to match itself. In any other location, the hyphen is used to identify a
range of ANSI characters.
• When a range of characters is specified, they must appear in ascending sort order
(from lowest to highest). [A - Z] is a valid pattern, but [Z - A] is not.
• The character sequence [ ] is ignored; it is considered to be a zero-length string.
The following table shows how to use Like to test expressions for different patterns using
special characters:
Number of Characters
Pattern
True
False
Multiple
"a*a"
"aa", "aBa", "aBBBa"
"aBC"
Special
"a[*]a"
"a*a"
"aaa"
Multiple
"ab*"
"abcdefg", "abc"
"cab", "aab"
Single
"a#a"
"a0a", "a1a", "a2a"
"aaa", a10a"
Range of characters
"[a - z]"
"f", "p", "j"
"2", "&"
Outside a range
"[^a - z]"
"9", "&", "%"
"b", "a"
Not a digit
"[^0 - 9]"
"A", "a", "&"
"0", "1"
Combined
"a[^b - m]#"
"An9", "az0"
"abc", "a99", "aj0"
Alternative branches
"yes|no"
"yes", yesterday", "no",
"albino"
"nothing", eyes",
"know", "grayest"
Note This operator returns all character strings with the same sequence, such as "No", "Non",
and "None".
219
220
Statements
Statements
While the standard functions and operators give most users powerful data manipulation
capabilities, you may need more advanced capabilities. The following types of statements
are supported for advanced formula processing:
• Flow Control Statements
• Option Math Statements
• Run-Time Error Trapping Statements
Information on additional statements and topics is also included:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Using DJX to Create SQL Statements
Declare Statement
Dim Statement
ElseIf Statement
For Each...Next Statement
For...Next Statement
Function Statement
Global Statement
Goto Statement
If...Then...Else Statement
Include Statement
On Error GoTo Statement
On Error Resume Next Statement
Option Base Statement
Option Explicit Statement
Option FieldExplicit Statement
Option FieldImplicit Statement
Option Implicit Statement
Option Math Fast Statement
Option Math Precise Statement
Option Math Strict Statement
ReDim Statement
Resume Statement
Resume Next Statement
Resume Label Statement
221
• Return Statement
• Select Case...End Case Statement
• While...Wend Statement
Flow Control Statements
Flow control is a term that describes more powerful and efficient ways to write
expressions. Conditional mapping and data modification are the primary reasons for
writing expressions.
To enter a flow control statement, double-click the desired statement from Script Editor.
For details on each statement, select from the following list:
•
•
•
•
•
•
•
•
•
•
ElseIf Statement
For Each...Next Statement
For...Next Statement
If...Then...Else Statement
Option Explicit Statement
Option FieldExplicit Statement
Option FieldImplicit Statement
Option Implicit Statement
Select Case...End Case Statement
While...Wend Statement
Example of Converting a Phone Number Format
These examples show how to convert a phone number to a (aaa) eee-nnnn format.
Expression 2 is much easier to write and read, and also processes more quickly and
efficiently. Expression 1 is not recommended, since the map must evaluate the entire IIf
statement before processing, while in If Then Else or Select statements, evaluation can
occur separately within each condition. For this reason, Expression 1 takes much longer to
process than Expression 2.
Expression 1
IIf(Trim(FieldAt("/SOURCE/R1/WorkPhone") ) <> "(",
IIf(Trim(FieldAt("/SOURCE/R1/WorkPhone") ) <> " ", "(" &
Left$(FieldAt("/SOURCE/R1/WorkPhone"), 3) & ")" &
Mid$(FieldAt("/SOURCE/R1/WorkPhone"), 4, 3) & "-" &
222
Statements
Right$(FieldAt("/SOURCE/R1/WorkPhone"), 4) , FieldAt("/SOURCE/R1/
WorkPhone") ), "" )
Expression 2
Select Case Left$(Trim(FieldAt("/SOURCE/R1/Field1")),1)
Case "("
FieldAt("/SOURCE/R1/Field1")
Case ""
FieldAt("/SOURCE/R1/Field1")
Case Else
"(" & Left$(FieldAt("/SOURCE/R1/Field1"), 3) & ")" &
Mid$(FieldAt("/SOURCE/R1/Field1"), 4, 3) & "-" &
Right$(FieldAt("/SOURCE/R1/Field1"), 4)
End Select
Option Math Statements
Option math statements specify how the map performs arithmetic operations. These
statements are transformation-level settings; once used, the statement remains in effect
throughout all expressions in a transformation, unless another statement changes the
setting.
The available option math statements include:
• Option Math Fast Statement
• Option Math Precise Statement
• Option Math Strict Statement
Calculations are either done with floating point or decimal values.
A number can be specified with &D in front of it (analogous to ‘&H’ to specify a hex
number). The &D specifies the number should be treated as a decimal number, and can
have up to 30 digits before the decimal point and up to eight after the decimal point.
Example
x=1234567890.123456789
FileWrite("Without using the &D prefix: " & x*1234567890.12)
If you do not use the &D prefix, a FileWrite writes the following result:
1524157875319615700
223
Whereas if you enter the following:
x=&D1234567890.123456789
FileWrite("Using the &D prefix: " & x*&D1234567890.12)
If you use the &D prefix, a FileWrite writes the following result:
1542157875319616034.31672002468
Run-Time Error Trapping Statements
These statements are available to assist you with run-time error trapping:
•
•
•
•
•
•
Goto Statement
On Error GoTo Statement
On Error Resume Next Statement
Resume Statement
Resume Next Statement
Return Statement
Using DJX to Create SQL Statements
DJX provides pragmatic information to the compiler. A pragma is an instruction to the
compiler to perform an action at compile time.
Use DJX to escape into the expression language where you can design SQL statements that
have meaning to the compiler. Otherwise, the SQL statement action is treated as a literal
SQL statement.
Dynamic SQL Statements
When you use DJX to escape into the expression language, you have the ability to build
your SQL statements dynamically. This is the same way that you build select statements
and stored procedure calls with the DJImport object using variables and source fields. This
method works for SQL statement actions in multimode and SQL steps in the Process
window.
Source query statements can also be built using DJX. These more complex expressions are
also covered in this chapter.
Example of SQL Statement with Integer and Character Data Types
In this example, an integer and a character are used intentionally. The character data
requires quoted identifiers, so this example will demonstrate how to use both integer and
character data types:
224
Statements
Create table TEST(
F1 int,
F2 char(10))
In a static SQL statement, the Insert action would be:
Insert into TEST (F1,F2) values (1,'hi')
If you want to use values or variables from some other source, you can use DJX to build the
insert statement dynamically. DJX, in its role as a pragma, tells the compiler that the SQL
statement must be resolved before it is sent to the database engine. Here is an example:
DJX("Insert into TEST (F1,F2) values (" & FieldAt("/SOURCE/R1/
Account No") & ",'" & variable & "')")
Note Although it wraps here, the entire expression is one line.
Review
Before you continue, pause here a moment and review the following points:
•
•
•
•
•
Values within the double quotes are literal strings.
The literal strings and the variables are concatenated in the result.
The integer value does not require double quotes.
The character data is enclosed in single quotes.
The first single quote follows the comma that separates the values to be inserted, and
both are within double quotes.
• The closing single quote, and the closing parenthesis (closes the values clause) follow
the last ampersand.
If FieldAt("/SOURCE/R1/ACCOUNT") equals 10019 and the variable value is "hello",
the SQL statement produced in DJX is:
Insert into TEST (F1,F2) values (10019,'hello')
This demonstrates how you can build a SQL statement dynamically using DJX to
incorporate values from field references and variables.
DJXBegin and DJXEnd
DJXBegin and DJXEnd are used together to define the boundaries of a more complex SQL
statement. Extending the utility of the DJX pragma, you can use DJXBegin and DJXEnd to
design multiple line SQL statements that contain Where or Values clauses.
225
Example
Here is an example of a source query statement with a Where clause based on the value
of a variable:
Select * from tester.TUTOR1
djxbegin
dim start
start = ""
Select Case var
case 1
start = " where ACCOUNTNO = 10019"
case 2
start = " where ACCOUNTNO = 10023"
case else
start = ""
End Select
return start
djxend
Review
Review the following points in this expression:
• DJXBegin tells the compiler that multiple lines of the expression language follow for
evaluation.
• The Select statement is static in this example.
• The Where clause is based on a Private variable named "var". (Passed into the
transformation map from a process.)
• If the variable does not match a value in the Select Case statement, the expression
returns the entire record set. ( start = "" )
• "Return start" appends the Where clause to the Select statement.
If the value of var is 1, the Query statement is:
select * from tester.TUTOR1 where ACCOUNTNO = 10019
226
Statements
Using DJXBegin, DJXEnd, and techniques from the DJX section you can build a Where
clause dynamically. The Where clause can be built for this example or for a Delete
statement as shown in the DJX section.
Source Query Statement
The source query statement requires that the variable be in scope before you run the
transformation. For details, search for “record events” and “transformation events” in the
documentation.
In our example above, the variable "var" must be instantiated and set prior to source
connection. Otherwise, Select Case does not find a matching value, defaults to start = ""
and returns the entire record set. To instantiate and set "var", here are a few options:
• Use a Private variable from a process to pass the value into the map.
• Use the FileRead() function to read an initialization file and set variable values by
parsing the values into the appropriate variable to dynamically build the SQL
statements. See FileRead Function.
See Also
Search for “variables” in the documentation.
Declare Statement
Description
Reference a function or sub-routine in an external library (DLL or
shared library)
Syntax
Declare Function publicname Lib "libname" [Alias "alias"]
[([[ByVal] variable [As type] [,[ByVal] variable [As type]]...])] As
Type
OR
Declare Subroutine publicname Lib "libname" [Alias "alias"]
[([[ByVal] variable [As type] [,[ByVal] variable [As type]]...])]
Remarks
The Declare statement can be used to call external code as if it
were an EZscript library artifact.
See Also
Adding EZscript Libraries
227
Dim Statement
Description
Dimension local variables
Syntax
Dim variablename
Remarks
The Dim statement uses the variablename argument.
Use Dim in a function procedure to declare variables that are
local to that procedure. Put your Dim statements at the
beginning of the procedure.
You must declare an object type, such as DJImport.
Limitation
There is no limitation of on the number of Private-level
variables. In most statements, Dim declares a Private-scoped
variable.
When used with a user-defined function, Dim create a functionscoped variable.
Example
This example uses the Dim statement to declare a variable in an
expression, where "Result" is the variable name. The If Then Else
statement is looking for Result A, else if Result A is not true, then
a Null is returned:
Dim Result
Result = UCase(Left(FieldAt("/SOURCE/R1/
Field1"), 1)
If Result = "A" then
Result = UCase(Left(FieldAt("/SOURCE/R1/
Field1"), 1)
Else
Result = ""
End If
Result
See Also
Scoping Variables
Note The Dim statement creates a local variable. This means that the Dim variable is local to
the expression in which it is defined. So, if you create a variable using the Dim statement in one
step, it is invisible to the all of the other steps in the transformation.
228
Statements
ElseIf Statement
Description
This variation of the If...Then...Else statement allows you to
choose from several alternatives. Adding clauses expands the
functionality of the If...Then...Else statement, so you can control
program flow based on different possibilities.
Syntax
If condition1 Then
[statementblock1]
[ElseIf condition2 Then
[statementblock2] ]
[Else
[statementblockn] ]
End If
Remarks
You can have as many ElseIf statements as you want in a block If,
but none can appear after the Else clause. Block If statements
can be nested; that is, contained within one another.
Another way to choose between several alternatives is the
Select Case statement.
Example
If(FieldAt("/SOURCE/R1/PRD_NO")) < 3000 Then
FieldAt("/SOURCE/R1/PRD_NO")
ElseIf FieldAt("/SOURCE/R1/PRD_NO") > 5000 Then
FieldAt("/SOURCE/R1/PRD_NO3")
Else
FieldAt("/SOURCE/R1/PRD_NO2")
End If
See Also
Statements and If...Then...Else Statement
229
For Each...Next Statement
Description
Repeat a group of statements for each element in an array or
collection.
This statement differs from the For . . . Next statement, in that
you iterate over the contents of a collection of objects without
the need to provide an index. Some ActiveX collections do not
provide a way to use indexes, so this statement is the only way
to use the contents of a collection.
Syntax
For Each index In container
[statementblock]
Next [index]
230
Statements
Remarks
The For . . . Each block is entered if there is at least one element
in container. Once the loop has been entered, all the statements
in the loop are executed for the first element in container. If
there are more elements in container, the statements in the
loop continue to execute for each element. When there are no
more elements in container, the loop is exited and execution
continues with the statement following the Next statement.
If the container is an object, it must resolve to an OLE container
object. If it is an OLE container, and the container contains
objects, the index variable must be DIMmed as an object also.
For each element in the container (array, enumerator for the
OLE container), the index variable is set to that value and the
statements executed.
You cannot use the For . . .Each . . . Next statement with an array
of user-defined types because a Variant cannot contain a userdefined type.
Any number of Exit For statements may be placed anywhere in
the loop as an alternative way to exit. Exit For is often used after
evaluating some condition. For example, an If …Then statement
would transfer control to the statement immediately following
Next.
Arguments and their descriptions follow:
• Index (required) - Variable used to iterate through the
elements of the collection or array. For collections, element
can only be a Variant variable, a general object variable, or any
specific object variable. For arrays, element can only be a
Variant variable.
• Container (required) - Name of an object collection or array
(except an array of user-defined types).
• statementblock (optional) - Any number of statements or
methods to be executed a specified number of times that are
executed on each item in container.
• Next [index] (optional) - Name of the index. If you omit index
in a Next statement, execution continues as if an index is
included. If a Next statement is encountered before its
corresponding For statement, an error occurs.
231
Example
This example uses the For Each...Next statement to display the
value of each element in a collection. Here, k is an element of
the collection named MyArr.
'Set up the array of numbers
Dim MyArr(4)
Dim j,k
For j = 0 to 4
MyArr(j) = j
Next j
'Cycle through each element in the array
For each k in MyArr
LogMessage(k)
Next
See Also
Search for “ActiveX” in the documentation.
Statements and For...Next Statement
Note You can nest For… Each … Next loops by placing one For ... Each ... Next loop within
another. However, each loop statement must be unique.
For...Next Statement
Description
Repeat a group of instructions a specified number of times
Syntax
For counter = start To end [ Step increment ]
[statementblock]
[Exit For]
[statementblock]
Next [counter [, counter]]
232
Statements
Remarks
To see the arguments for the For...Next statement, see the table
following this one.
The Step value controls loop execution is as follows:
• When Step is Positive or 0, the Loop executes if counter <= end
• When Step is Negative, the Loop executes if counter >= end
Once the loop has been entered and all the statements in the
loop have executed, Step is added to counter. At this point,
either the statements in the loop execute again (based on the
same test that caused the loop to execute in the first place), or
the loop is exited and execution continues with the statement
following the Next statement.
Important: Changing the value of counter while inside a loop
can make the program more difficult to read and debug.
Example
You can nest For...Next loops by placing one For...Next loop
within another. Give each loop a unique variable name as its
counter. The following construction is correct:
For I = 1 To 10
For J = 1 To 10
For K = 1 To 10
...
Next K
Next J
Next I
A Next statement with the form Next K, J, I is equivalent to the
following sequence of statements:
Next K
Next J
Next I
See Also
Statements
Argument
Description
counter
Numeric variable used as the loop counter. The variable cannot be an array
element or a record element.
start
Initial value of the counter.
233
Argument
Description
end
Final value of the counter.
increment
The amount the counter is changed each time through the loop. If you do not
specify Step, increment defaults to 1.
statement block
Any number of statements or methods to be executed a specified number of
times.
Note If you omit the variable in a Next statement, the value of Step increment is added to the
variable associated with the most recent For statement. If a Next statement is encountered
before its corresponding For statement, an error occurs.
Function Statement
Description
Declares the name, arguments, and code that form the body of
a function procedure.
Syntax
Function functionname [(argumentlist)]
[statementblock]
[functionname = expression]
[Return]
[statementblock]
[functionname = expression]
End Function
234
Statements
Remarks
All executable code must be in Function procedures. You cannot
define a function procedure inside another Function procedure.
The Function statement arguments are detailed in the table
below this one.
Function and End function mark the beginning and end of a
function procedure, respectively.
You can call a function procedure by using the function name,
followed by the argument list in parentheses, in an expression. If
the function has no arguments, you still must include the
parentheses.
Variables used in Function procedures fall into two categories:
those that are explicitly declared within the procedure and
those that are not. Variables that are explicitly declared in a
procedure (using Dim or an equivalent) are always local to the
procedure. Other variables used but not explicitly declared in a
procedure are also local unless they are explicitly declared at
some higher level outside the procedure.
Example
To return a value from a function, assign the value to the
function name. For example, in a function named BinarySearch,
you could assign the value of the constant False to the name to
indicate that the value was not found:
Function BinarySearch(...)
...
' Value not found. Return a value of False.
If lower > upper Then
BinarySearch = False
Return
End If
End Function
See Also
Statements
235
Argument
Description
functionname
Name of the function. Function procedure names follow the same naming conventions
as other variables and can include a type-declaration character. Functionname cannot
be the same as any other globally recognized name in the program. Such names include
the names of procedures (in Basic or a dynamic-link library [DLL]), Private variables, and
Global constants.
argumentlist
List of variables, representing arguments, that are passed to the function procedure
when it is called. Multiple variables are separated by commas.
statementblock
Any group of statements that are to be executed within the body of the function
procedure.
expression
Return value of the function. A function procedure returns a value by assigning that
value to the function functionname. Any number of such assignments can be used
anywhere within the procedure. If no value is assigned to functionname, the procedure
returns a default value: A numeric function returns 0, a String function returns a zerolength string (""), and a Variant function returns Empty.
return
The Return statement causes the immediate termination of the function (See Return
Statement.) Program execution resumes with the statement after the calling statement.
The argument argument list has the following syntax:
variable[( )] [,variable[( )]] . . .
It uses the arguments listed in the table below.
Argument
Description
variable
Name of the variable representing the argument. For array variables, use the
parentheses but omit the number of dimensions.
Caution Function procedures can be recursive; that is, they can call themselves to
perform a given task. However, recursion can lead to stack overflow. In addition, there is a
32 parameter limitation in functions, and if this limitation is exceeded, stack overflow
occurs. For more information, see Stack Overflow.
A procedure can use a variable that is not explicitly declared in the procedure, but a name
conflict can occur if anything you have defined in the Declarations section has the same
name. If your procedure refers to an undeclared variable that has the same name as
another procedure, a Private-level constant or variable, or an object, Basic assumes that
your procedure is referring to that Private-level name. Explicitly declare variables to avoid
236
Statements
this kind of conflict. You can use an Option Explicit statement to force explicit declaration
of variables. See Option Explicit Statement.
Global Statement
Note This statement has been deprecated. We encourage you to use either Public or Private
variables instead of Global. Global is synonymous with Private. Private variables are variables
that are global to a step, but are not shared by all steps in a process.
Description
Declare global variables (variables that are available to all
procedures). That is, a global variable may be used by any
expression written in any/all target field expressions for any/all
target fields.
Syntax
Global variablename
Remarks
The Global statement uses these arguments:
ArgumentDescription
variablenameName of a variable.
ExampleGlobal x
x=7
See Also
Statements
Search for “variables” in the documentation.
Goto Statement
Description
Cause execution to branch to a label
Syntax
Goto label
237
Remarks
A label must be all alphanumeric characters, begin in column 1
and end with a colon.
Do not use the Goto statement to jump into or out of Select
statements or For loops.
If a Goto statement tries to jump in to a Select statement or a For
loop, a compile-time undefined label error is generated.
If a Goto statement tries to jump out of a Select statement or a
For loop,
an error stating 'attempt to jump out of XXX", where 'XXX'
describes the loop/block type.
Example
‘This statement causes run-time execution to jump to the label
"here":
Goto here
See Also
On Error GoTo Statement, Resume Statement, Resume Next
Statement, and Return Statement
If...Then...Else Statement
Description
Allow conditional execution, based on the evaluation of an
expression
Syntax 1
If condition Then thenpart [Else elsepart]
The single-line form of If...Then...Else is often useful for short,
simple conditional tests.
Part
Description
condition
A numeric or string expression
that evaluates true (nonzero)
or false (0 or Null).
thenpart, elsepart
Statements or branches
performed when condition is
True (thenpart) or False
(elsepart).
The thenpart and the elsepart fields both have this syntax:
{statements | [GoTo] linenumber | GoTo linelabel}
The thenpart and elsepart syntax has these parts:
Part
238
Description
Statements
statements
One or more Access Basic
statements separated by
colons (:)
linenumber
A valid program line number
linelabel
A valid program line label
The thenpart is executed if condition is true; if condition is false,
then elsepart is executed. If the Else clause is not present,
control passes to the next statement in the program.
You can have multiple statements with a condition, but they
must be on the same line and separated by colons, as in the
following statement:
If A > 10 Then A = A + 1 : B = B + A : C = C + B
Syntax 2
If condition1 Then
[statementblock1]
[ElseIf condition2 Then
[statementblock2] ]
[Else
[statementblockn] ]
End If
The block form of If...Then...Else provides more structure and
flexibility than the single-line form and is usually easier to read,
maintain, and debug. It has the following parts:
Part
Description
condition1, condition2
The same conditions as used in
the single-line form.
statementblock1 to n
One or more Access Basic
statements on one or more
lines.
239
In executing a block If, the map tests condition1, the first
numeric expression. If the expression is true, the statements
following Then are executed. If the first expression is false, the
map begins evaluating each ElseIf condition in turn. When the
map finds a true condition, the statements following the
corresponding Then are executed. If none of the ElseIf
conditions is true, the statements following Else are executed.
After executing the statements following Then or Else, the
program continues with the statement following End If.
The Else and ElseIf blocks are both optional. You can have as
many ElseIf clauses as you like in a block If, but none can appear
after an Else clause. Any of the statement blocks can contain
nested block If statements.
The map looks at what appears after the Then reserved word to
determine whether or not an If statement is a block If. If
anything other than a comment appears after Then, the
statement is treated as a single-line If statement.
A block If statement must be the first statement on a line. The
Else, ElseIf, and End If parts of the statement can have only a line
number or line label in front of them. The block must end with
an End If statement.
Remarks
Use the If… Then… Else statement to define two blocks of
statements. One of the statements runs when the specified
condition is True, and the other one runs when the condition is
False. When you want to define more than two blocks of
statements, use the ElseIf Statement.
You can nest up to ten levels of If... Then... Else statements. If you
need to create an expression with more than ten levels, you
must redefine it using the ElseIf statement or the Select
Case...End Case Statement.
240
Statements
Example
This example tests the length of a field after spaces have been
removed to determine if the field contains data. If the source
field contains no data, a string is placed in the target field that
says No Data Available. If there is data in the source field, the
data is placed in the target field.
If Len(Trim(FieldAt("/SOURCE/R1/Field1")))=0
Then
"No Data Available"
Else
FieldAt("/SOURCE/R1/Field1")
End if
See Also
Select Case...End Case Statement GSub Function, IIf Function,
StrReplace Function, Sub Function, and Transliterate Function
Include Statement
Description
Opens and reads a file during compilation, inserting the
contents of the file as part of the program.
Syntax
Include "filename"
Remarks
The file name must be a string literal.
Example
‘This statement returns the contents of the tutor1.asc file:
Include "tutor1"
On Error GoTo Statement
Description
Cause a trappable run-time error to jump to a label
Syntax
On Error GoTo...
Remarks
Various parameters indicate how errors are handled. Error
trapping is turned off while in the body of the error-handler
routine. If a run-time error occurs while processing the original
error, execution is terminated immediately.
You may find out what error was trapped by accessing the Err
object. The number and description properties of the Err object
are accessed in the same way as they are in Visual Basic.
Err.number is the error number and Err.description is the error
description. These properties can only be read, not modified.
241
Example
‘This turns error trapping off, so a run-time error is a terminal
condition:
On Error GoTo 0
'This causes a trappable run-time error to jump to the label
"errlabel":
On Error GoTo errlabel
See Also
Goto Statement, Resume Statement, Resume Next Statement,
and Return Statement
Note Run-time error handling is not scoped as it is in Visual Basic. If an error occurs in a userdefined function, and that function does not have an error handler, then any error handling in
the caller is NOT activated. Instead, the run-time error causes immediate termination of
processing. Control may fall through into an error handler, but in this case, you should not try
to execute a Resume or Resume Next statement, as that causes an immediate, untrappable
run-time error.
On Error Resume Next Statement
Description
Cause a trappable run-time error to jump to the next line
Syntax
On Error Resume Next...
Remarks
Various parameters indicate how errors are handled. Error
trapping is turned off while in the body of the error-handler
routine. If a run-time error occurs while processing the original
error, execution is terminated immediately.
You may find out what error was trapped by accessing the Err
Object Variable. The number and description properties of the
Err object are accessed in the same way as they are in Visual
Basic. Err.number is the error number and Err.description is the
error description. These properties can only be read, not
modified.
Example
This causes a trappable run-time error to skip the rest of the
currently executing statement:
On Error Resume Next
See Also
242
Goto Statement, On Error GoTo Statement, Resume Statement,
Resume Next Statement, and Return Statement
Statements
Option Base Statement
The Option Base statement has no effect on an array declared with explicit bounds.
Description
Explicitly set the default lower bound for all array subscripts
Syntax
Option Base {0 | 1}
Remarks
The base of an array is the index value of its lower bound.The
default base (lower bound) of an array is 0.
In a five-element, one-dimensional array, the lower bound is 0
and the upper bound is 4.
A five-element, one-dimensional array using Option Base 1 has
a lower bound of 1 and an upper bound of 5.
See the table below for examples.
Statement
Dimensions
Lower
Bound
Upper
Bound
Elements
Option Base 0
1
0
4
5
Option Base 1
1
1
5
5
Option Base not used
1
0
4
5
Dim myarray (0 to 3)
1
0
3
4
The Option Base statement is not required. Use Option Base to explicitly set an array lower
bound to 1.
If used, the Option Base statement must appear before any array declarations.
Use the To clause when you declare an array for more flexible control of the range of its
subscripts.
Option Explicit Statement
Description
Require variables be declared before they are first used
Syntax
Option Explicit
243
Remarks
The Option Explicit statement tells the expression language to
require the use of a Dim, Public, or Private statement. It is
usually the first statement in an expression, so it is used more as
a policy setting rather than a property that is turned on and off.
The default is Option Implicit.
The Option Implicit statement, which does not require that
variables be declared before they are first used, is the default
behavior.
Option Explicit applies to the entire “expression context”,
excluding Process steps and Transformation steps. Expression
context is defined as either the entire conversion, or all
expressions in a context.
If you use variables in functions elsewhere (such as target field
expression or BeforeTransformation event) you must use the
Option Explicit statement in your expressions each time.
Example
This statement, which includes Option Explicit, generates an
error at run time, since the declared variable name is misspelled.
If the Option Explicit function is not used, the error is simply
written as an error message in the log. The compiler does not
error out, since it automatically defines the misspelled variable
name for you. It is, therefore, useful to always use Option
Explicit when declaring variable names in a transformation.
Option Explicit
Dim srvr_name$
srvr_name$ = "NTServer"
Print "Using server " & svr_name$
'^^^
'undefined variable name
See Also
Option Implicit Statement
Tip It is a good practice to declare Option Explicit statements at the beginning of your
script. Then call the script file in the expression. This file may then be shared between
modules in multiple transformations. It is more efficient to declare Private variables once
in a script file, rather than declaring them in each transformation script. .
244
Statements
Option FieldExplicit Statement
Description
Cause transformation to error if field elements do not exist
Syntax
Option FieldExplicit
Remarks
This can be set in the BeforeTransformation event, and applies
to all code modules. If it is to be used in a single code module, it
is usually the very first statement in that module. When writing
user-defined functions, Option FieldExplicit is the default
behavior.
To treat missing elements as Nulls, use the Option FieldImplicit
statement.
See Also
Option FieldImplicit Statement
Option FieldImplicit Statement
Description
Cause transformation to treat missing field elements as Null
Syntax
Option FieldImplicit
Remarks
This can be set in the BeforeTransformation event, and applies
to all code modules. If it is to be used in a single code module, it
is usually the very first statement in that module. When writing
user-defined functions, Option FieldExplicit is the default
behavior.
See Also
Option FieldExplicit Statement
Option Implicit Statement
Description
Turn off the requirement that variables be declared before they
are first used
Syntax
Option Implicit
245
Remarks
This is usually the very first statement in a code module, so it is
used more as a policy setting rather than a property that gets
turned on and off.
When writing user-defined functions, keep in mind that Option
Implicit is the default behavior. Use of Option Implicit's opposite,
the Option Explicit statement, is recommended, since Option
Explicit requires that variables be declared before they are used.
For more information, see the tip in Option Explicit Statement.
Example
This program simply results in a bug in the code. The interpreter
does not complain, since it would just automatically define the
misspelled variable name for you.
srvr_name$ = "NTServer"
Print "Using server " & svr_name$
'
^^^
'
undefined variable name
Option Math Fast Statement
Description
If both operands are longs, the map performs long (32-bit
integer) arithmetic. If either operand is a floating point number,
the arithmetic is performed as floating point.
Syntax
Option Math Fast
Remarks
Math is performed using floating point values, since they are
much faster than decimal values.
This statement is a context-setting at the transformation level. If
Option Math Fast is used once, the setting remains in effect for
all expressions in a transformation, unless another statement
changes the setting.
See Also
Option Math Precise Statement and Option Math Strict
Statement
Option Math Precise Statement
246
Description
Perform decimal arithmetic
Syntax
Option Math Precise
Statements
Remarks
This statement is used to force decimal arithmetic, unless one of
the operands is a floating point number. In this case, the math is
done as floating point. If the result overflows or underflows, it
converts both numbers to floating point and tries again.
This statement is a context-setting at the transformation level. If
Option Math Precise is used once, the setting remains in effect
for all expressions in a transformation, unless another statement
changes the setting.
See Also
Option Math Fast Statement and Option Math Strict Statement
Option Math Strict Statement
Description
Perform decimal arithmetic
Syntax
Option Math Strict
Remarks
This statement is similar to Option Math Precise, however, if an
overflow or underflow occurs, a run-time error is generated
(instead of transformation of the numbers to floating point).
This statement is a context-setting at the transformation level. If
Option Math Strict is used once, the setting remains in effect for
all expressions in a transformation, unless another statement
changes the setting.
See Also
Option Math Fast Statement and Option Math Precise
Statement
ReDim Statement
Description
Resize an array variable
Syntax (one dimension)
ReDim [Preserve] ArrayName(UpperBound)
ReDim [Preserve] ArrayName(LowerBound To
UpperBound)
Where ArrayName is the array variable name; UpperBound is
the new UpperBound of the array; LowerBound is the index
number of the first element; UpperBound is the index number
of the last element.
Preserve is an optional keyword used to preserve the data in an
existing array when you change the size of the last dimension.
247
Syntax (multi-dimensional)
ReDim [Preserve]
ArrayName(Dimension1[,Dimension2][,Dimension3])
ReDim [Preserve] ArrayName(LowerBound1 To
UpperBound1 [,LowerBound2 To UpperBound2][,
LowerBound3 To UpperBound3])
Where ArrayName is the array variable name; Dimension1 is the
size, in elements, of the array's first dimension; Dimension2 is
the size, in elements, of the array's second dimension (optional);
Dimension3 is the size, in elements, of the array's third
dimension (optional). LowerBound and UpperBound are the
upper and lower bounds of the respective array dimensions.
Preserve is an optional keyword used to preserve the data in an
existing array when you change the size of the last dimension.
Remarks
The ReDim statement is used to resize an array that has already
been explicitly declared using the Dim, Private, or Public
statement. You can use the ReDim statement repeatedly to
change the number of elements and dimensions in an array.
If you use the Preserve keyword, you can only resize the last
array dimension and you can't change the number of
dimensions at all. If your array has two dimensions, you can only
change the number of elements in the second (last) dimension
and still preserve the contents of the array. If you make an array
smaller than it was, data in the eliminated elements are lost.
When you use Preserve, you can change the size of the array
only by changing the upper bound; attempting to change the
lower bound results in an error. Element values are lost when
ReDim is used without Preserve.
The ReDim statement destroys the existing array and creates
another array from scratch. Therefore, if the Preserve keyword
is not used, all values in the array are lost.
Limitations
Variables may NOT be used as size placeholders when initially
declaring an array. For example, Dim MyArray(VariableName) is
illegal.
Arrays are limited to three dimensions. For more information on
arrays, see Dimensions of Variables.
248
Statements
Example
' Creates a 1-dimension array with 5 elements
Dim MyArray(1 To 4)
' Resizes the array by adding 5 more elements
ReDim MyArray(1 To 9)
' Illegal, results in an error
ReDim MyArray(0 To 9)
See Also
Dim Statement
Resume Statement
Description
Cause execution to branch back to the beginning of the
statement in which the run-time error occurred
Syntax
...Resume...
Remarks
This statement is executed while in the body of an error handler.
It causes error trapping to be restored to its previous state, for
example: Resume Next or Goto errlabel. If this statement is
executed while an error handler is not active, an untrappable
run-time error occurs.
Error trapping is turned off while in the body of the error
handler routine. So if a run-time error occurs while processing
the original error, execution is terminated immediately.
Example
On Error Resume
See Also
Goto Statement, Resume Next Statement, On Error GoTo
Statement, and Return Statement
Resume Label Statement
Description
Cause execution to branch back to the statement containing the
label
Syntax
…Resume [Label]
249
Remarks
This statement is executed while in the body of an error handler.
It causes error trapping to be restored to its previous state, for
example: Goto errlabel. If this statement is executed while an
error handler is not active, an untrappable run-time error
occurs.
Error trapping is turned off while in the body of the errorhandler routine. If a run-time error occurs while processing the
original error, execution is terminated immediately.
Note: Labels must be left-justified. The label Errhandler cannot
be indented in an expression. If labels are indented, an
"undefined label" error occurs at run time.
Example
This example causes the compiler to branch back to the Cont1
part of the code:
On Error GoTo ErrHandler
Dim Var
Var = FieldAt("/SOURCE/R1/Customer")
Cont1:
Var = "No ID"
LogMessage(Var)
Return
ErrHandler:
LogMessage("in ErrHandler")
Resume Cont1
See Also
Goto Statement, Resume Statement, On Error GoTo Statement,
Return Statement, and Resume Next Statement
Resume Next Statement
Description
Cause execution to branch back to the beginning of the
statement after the statement in which the run-time error
occurred
Syntax
…Resume Next
Remarks
This statement is executed while in the body of an error handler.
It causes error trapping to be restored to its previous state, for
example: Goto errlabel. If this statement is executed while an
error handler is not active, an untrappable run-time error
occurs.
Error trapping is turned off while in the body of the errorhandler routine. If a run-time error occurs while processing the
original error, execution is terminated immediately.
250
Statements
Example
This causes a trappable run-time error to skip the rest of the
currently executing statement.
On Error Resume Next
See Also
Goto Statement, Resume Statement, On Error GoTo Statement,
and Return Statement
Return Statement
Description
Allow processing in the "main module" of an expression to
return early
Syntax
Return expr
OR
... Return
Remarks
Return alone works exactly as if the end of the expression is
reached; any value left on the stack will end up being the return
value. If a value is placed in the expr argument, then that value
is explicitly specified to be returned.
Example
The following causes the expression to terminate with the value
25 as the Return value:
...
25
Return
The following causes the expression to terminate with the value
37 as the Return value:
...
Return 37
See Also
Goto Statement, Resume Statement, On Error GoTo Statement,
and Resume Next Statement
251
Select Case...End Case Statement
Description
Conditionally execute one of several statement blocks,
depending on the value of an expression
Syntax
Select Case testexpression
[Case expressionlist1
[statementblock1] ]
[Case expressionlist2
[statementblock2] ]
...
[Case Else
[statementblockn] ]
End Select
Remarks
If testexpression matches the expressionlist associated with a
Case clause, the statement block following that Case clause is
executed up to the next Case clause, or for the final one, up to
End Select. Control then passes to the statement following End
Select.
You can use multiple expressions or ranges in each Case clause.
You also can specify ranges and multiple expressions for
character strings.
If testexpression matches more than one Case clause, only the
statements following the first match are executed.
Select Case statements can be nested. Each Select Case
statement must have a matching End Select statement.
The expression list that follows the Case in a Select Case
statement must be a list of constant numeric or string
expressions. If you want to use variables for different cases, use
the If...Then...Else Statement instead.
252
Statements
Example 1
‘The following expression converts the data in the RepNumber
field from the value contained in the source file to a new value
in the target file:
Select Case FieldAt("/SOURCE/R1/RepNumber")
Case 44
"32"
Case 43
"33"
Case 0
"33"
Case Else
"33"
End Select
Example 2
‘To use a combination of a set of values and a nested select case:
Select CaseFieldAt("/SOURCE/R1/category")
Case "005","009","004","008","010"
"P"
Case "001","003","007","002"
"R"
Case "006"
Select Case FieldAt("/SOURCE/R1/method")
Case "MX"
"A"
Case else
"P"
End Select
Case Else
"X"
End Select
Example 3
‘Look for certain characters:
Select CASE MyVariable
CASE "}", ">", ")"
GSub("[}>)]", "", FieldAt("/SOURCE/R1/
Field1"))
CASE Else
FieldAt("/SOURCE/R1/Field1")
End Select
253
Example 4
‘Look for a value greater than a certain number:
Select CASE FieldAt("/SOURCE/R1/Field1")
CASE IS > 3
FieldAt("/SOURCE/R1/Field1") - 2
CASE Else
FieldAt("/SOURCE/R1/Field1")
End Select
Example 5
‘Choose a value between two numbers:
Select CASE 88
CASE IS <= 69
"D"
CASE 70 To 79
"C"
CASE 80 To 89
"B"
CASE Else
"A"
End Select
See Also
Statements and Flow Control Statements
Argument
Description
testexpression
Any numeric or string expression
statementblock
The elements statementblock1 to statementblockn consist of
any number of statements on one or more lines.
expressionlist
These elements can take any of the following three forms:
• expression [, expression]
• expression To expression
• Is comparison-operator expression
254
Part
Description
expression
Any numeric or string expression. The type of the expression must
be compatible with the type of testexpression. (The type of the
expression is coerced to the same type as testexpression. For
example, if testexpression is an integer, expressionlist can contain
a double-precision data type.)
comparison-operator
Any valid comparison operator, except the Like operator.
Statements
While...Wend Statement
Description
Execute a series of statements in a loop as long as a given
condition is true
Syntax
While condition
[statementblock]
Wend
Remarks
The argument condition is a numeric or string expression that
evaluates True (nonzero) or False (0 or Null).
If condition is true, all statements in statementblock are
executed until the Wend statement is encountered. Control
then returns to the While statement and condition is checked
again. If condition is still true, the process is repeated. If it is not
true, execution resumes with the statement following the Wend
statement.
While...Wend loops can be nested to any level. Each Wend
corresponds to the most recent While.
Example
This example uses While...Wend to print the numbers 1 through
4:
A = 1
While A < 5' Begin loop.
Print A' Print A.
A = A + 1' Increment A.
Wend
See Also
If...Then...Else Statement, For...Next Statement, Select
Case...End Case Statement and Statements
Caution Do not branch into the body of a While...Wend loop without executing a While
statement. Doing so may cause run-time errors or problems that are difficult to locate.
255
256
Variables
Variables
Variables in Data Integrator allow you to reference values or expressions in your script.
When you declare a variable, you must include its scope, name, type, and dimension.
Note Constants are evaluated only at the beginning of a transformation, whereas variables are
evaluated each time they are called.
This section includes the following topics:
•
•
•
•
•
•
•
Scoping Variables
Guidelines for Naming Variables
Variant Data Type
Dimensions of Variables
Adding Variables
Importing Variables
Clearing Variables and Array Elements
Scoping Variables
Data Integrator supports declaring variables in the three scope levels of local, private, and
public, as shown in this table.
257
Scope Level
How Declared
Script Example
Extent of Existence
Local
(default)
Use Dim inside a function or at
the beginning of a module
Function Y
Available within a function or at
the beginning of a module.
Dim X
End Function
OR
Dim X
Function A
End Function
Function B
End Function
Private
Private
Private X
The data type can also be
specified after "as”.
OR
Note: Global declaration is still
supported for backwardcompatibility, but Private is the
preferred syntax.
Public
Global X
OR
Private X as
DJImport
Public
Public X
The data type can also be
specified after "as".
OR
Public X as Object
Available to all expressions
within a single process or map.
Note: Be cautious when using
any function that declares a
private variable within a
process. If you call that function
from a Process step, the
function fails since it is not able
to access the private variable.
Available to all expressions or
maps within a process, except
maps called from Process steps.
In that case, the Public variable
must also be declared within
the Process steps.
Local Scope Notes
A local variable is local to the expression in which it is defined. So, if you create a variable
using the Dim statement in one step of a process, its contents are not available to other
process steps.
If you want to create a local variable to use in multiple expressions or steps within a
process, you must create multiple local variables, each with the same name. Each of the
expressions or steps needs its own Dim statement.
A better method for sharing the same variable among multiple steps is to declare the
variable as either Private or Public.
258
Variables
Public Scope Notes
Public variables are available within a process and to all transformations and steps within
that process. For example, values can be passed from one transformation to another or
from a Decision step to a Script step.
Keep the following in mind when working with public variables:
• Public variables are not available to transformations within Process steps unless they
are also declared within the Process steps.
• To execute a transformation independently from the Map window, from the command
line, or if you want to be able to test that step only, declare the same public variable
in one of the modules inside the Map window.
• To test a Transformation step that contains an undeclared but referenced Public
variable, select the step that contains the variable declaration along with the
Transformation step. Then test both steps together. This allows the transformation to
execute properly.
See Also
Guidelines for Naming Variables
Variant Data Type
Dimensions of Variables
Adding Variables
Clearing Variables and Array Elements
Statements that let you control variables:
Option Explicit Statement
Option Implicit Statement
Guidelines for Naming Variables
Variable names may use alphanumeric characters and underscores, but no spaces or
hyphens, and the first character must not be numeric.
See Also
Scoping Variables
Variant Data Type
Dimensions of Variables
Adding Variables
259
Clearing Variables and Array Elements
Variant Data Type
Data Integrator offers many data types, covering many types of data. Some of the types
relate to data structures from other programming languages, while some are internal.
Note You cannot declare anything as Integer or a Long data type with EZscript. The advantage
of this is that it simplifies the expressions. The disadvantages are that certain pieces of code
using variant may process a little more slowly than others, or may not catch certain classes of
programming errors.
The default data type is variant. Variant is a self-describing data type that can hold simple
numeric or string values. Variants can also make additional distinctions about numeric
information. Global variables of the variant data type have initital values that you can
overrite in configurations.
Data Integrator variants can hold numeric information ranging in size from a Boolean byte
to complex values like text. These categories within a variant are called subtypes.
Variant subtypes broaden the list of possible types of data. This table shows the subtypes
that variants can contain.
Name
Internal Size
Value Range
Text
2*(len+1) + overhead in
Windows 4*(len+1) + overhead
in Unix
Up to 2 billion characters in Windows (32- and 64-bit)
2 bytes
16-bit signed or unsigned binary integer, therefore range
is:
Short
Up to 2^64 characters in 64-bit Unix
Unsigned: 0 to 65535
Signed: -32768 to 32767
Integer
4 bytes
32-bit signed or unsigned binary integer, therefore range
is:
Unsigned: 0 to 4294967295
Signed: -2147483648 to 2147483647
Float
260
8 bytes
Precision of about 16 digits. Standard IEEE 64-bit floating
point.
Variables
Name
Internal Size
Value Range
Decimal
Varies
Precision of 76; scale of 38
Actual size depends on output format.
Date
12 bytes
For value range, see comments for DateTime. Based upon
DateTime with a time of 0.
Time
12 bytes
For value range, see comments for DateTime. Based on
DateTime with a date of 0.
DateTime
12 bytes
DateTime can represent date and time to nanosecond
precision, starting with January 1, 1 AD.
Julian to Gregorian transition uses England-Scotland
transition, where September 14, 1752, immediately
follows September 2.
Boolean
1 byte
True or False
Name
Varies
A string parsed into these name parts:
• honorific
• first
• middle
• last
• title
Quadword
8 bytes
32-bit signed or unsigned binary integer, therefore range
is:
Unsigned: 0 to 18446744073709551615
Signed: -9223372036854775808 to
9223372036854775807
Interval
32 bytes
Range depends on output format and interval type.
Dimensions of Variables
A variable with the array dimension is a single variable with many compartments to store
values. Unlike an array, a scalar variable has one compartment that can store only one
value. Both scalar and array variables are declared using the Dim, Private, or Public
statement.
To store the names of all the months you can declare 12 scalar variables.
Private Month1
Month1 = "January"
261
Private Month2
Month2 = "February"
Private Month3
Month3 = "March"
...
Private Month12
Month12 = "December"
However, this method requires coding a large number of types. Using an array is a more
elegant and efficient way to store a group of related values.
Referencing Elements in Arrays
Arrays can have up to three dimensions and up to 1,000,000 elements. Each element of an
array stores one value and is referenced by its index (coordinate position). The index of the
first element of an array is called its lower bound, while the index of the last element is
called its upper bound.
By default, an array is indexed beginning with zero. The declaration must include the
number of elements inside parentheses. In the months example, the lower bound is zero,
while the upper bound is 11. The upper and lower bounds of an array can be inspected
using the LBound and UBound keywords.
For arrays with more than one dimension, the index of each dimension must be included
to reference an individual element.
The entire array can be referenced using just the array name, with no index. This is useful
for assigning the same value to every element or clearing all the values in the array.
Declaring Arrays
To declare an array, use the Dim, Private, or Public statement with the array name, then
include the size in parentheses. Upper and lower bounds can be explicitly declared using
the To clause.
Example of Syntax (one dimension)
{Dim | Private | Public} ArrayName(UpperBound)
{Dim | Private | Public} ArrayName(LowerBound To UpperBound)
Where ArrayName is the array variable name; NumberOfElements is the size, in elements,
of the array; LowerBound is the index number of the first element; UpperBound is the
index number of the last element.
262
Variables
Example of Syntax (multidimensional)
{Dim | Private | Public}
ArrayName(Dimension1[,Dimension2][,Dimension3])
{Dim | Private | Public} ArrayName(LowerBound1 To UpperBound1
[,LowerBound2 To UpperBound2][,LowerBound3 To UpperBound3])
Where ArrayName is the array variable name; Dimension1 is the size, in elements, of the
array's first dimension; Dimension2 is the size, in elements, of the second dimension
(optional); Dimension3 is the size, in elements, of the third dimension (optional).
LowerBound and UpperBound are the upper and lower bounds of the respective array
dimensions.
Limitations
Variables may not be used as size placeholders when initially declaring an array. For
example, Dim MyArray(VariableName) is illegal.
A map checks for the following at run time:
• Upper/lower bounds (+1) are not greater than the limit of 32,728 in each dimension
• The total number of elements (all dimensions multiplied together) is not greater than
the 100,000-element limit for arrays
Remarks
Whether an array is indexed from 0 or 1 depends on the setting of the Option Base
statement. If Option Base 1 is not specified, all array indexes begin at zero. The Option Base
statement has no effect on arrays declared with explicit bounds.
Note When you declare a Dim statement for arrays, be aware that the number of elements is
always one greater than the upper bounds because the index starts with zero. For example, if
you need five placeholders, dimension your array with a four and index it as (0), (1), (2), (3) and
(4).
The lower bound of an array can be determined with the LBound function. The upper
bound of an array can be determined using the UBound function.
Tip Use an ExecuteExpression action with the TransformationStarted event to declare an
array with the Private statement. This creates an array that exists throughout the
transformation, allowing you to use it and the values of its elements across multiple fields
and records.
263
To dynamically size an array, initially declare it without a size or explicit bounds. When the
number of elements required is known, use the ReDim statement to resize the array.
See Also
ReDim Statement
LBound Function
UBound Function
Storing Data in Arrays
Assigning values to an element in an array is similar to assigning values to scalar variables.
Simply reference an individual element of an array using the array name and the index
inside parentheses, then use the assignment operator (=) followed by a value. Until an
array element is first assigned a value, it has a Null (empty) value.
In the months example, the values are set as follows:
Month(0) = "January"
Month(1) = "February"
Month(2) = "March"
...
Month(11) = "December"
With larger arrays, assigning each element individually is tedious. A more efficient way to
accomplish this task is to use a scalar variable to store a counter value and a For...Next
statement to loop through the elements. The index of the element is then dynamically
referenced using that counter variable.
' Declare a 1-dimension array and a counter variable
Public MyArray(4)
Public X
' Loop through the array to assign values
For X = 0 To 4
MyArray(X) = X * 5
Next X
264
Variables
For two- or three-dimension arrays, multiple For...Next statements and counter variables
can be nested to loop through all the elements, in each dimension.
' Declare a 2-dimension array and counter variables
Public MyArray(5,10)
Public X
Public Y
' Loop through the 2nd dimension of the array
For Y = 0 To 10
' Loop through the 1st dimension of the array
For X = 0 To 5
MyArray(X,Y) = X * Y
Next X
Next Y
The array indexes can be combined with metadata expressions to assign values from a
source record to elements in an array. The following example loads the first four fields of
the file into a 1-dimension array:
Map Window / TransformationStarted Event / ExecuteExpression Action
' Declare a 1-dimension array and a counter variable
Public MyArray(3)
Public X
265
Map Window / Source Record Layout 1 / RecordEnded Event / ExecuteExpression Action
Assign a target field a value from the array. Create this expression for the target field 2:
MyArray(2).
' Loop through the four array elements and copy their values
' to the first four target fields
For X = 0 To 3
FieldAt(/SOURCE/R1/X+1) = MyArray(X)
Relative field positions start counting at one, unlike the default lower bound for array
indices, which is zero. In order to use the same counter variable to loop through both the
array elements and the source fields, the value of that counter must be incremented by 1
before it is used to reference the field position. Alternatively, the default lower bound for
arrays can be changed to 1 using the Option Base statement.
Since the array is loaded with the RecordEnded event, the values of each array element get
refreshed with each new source record.
Retrieving Data from Arrays
Retrieving values from array elements is similar to retrieving values from scalar variables.
Simply list the variable name where the value should be copied, followed by the
assignment operator (=), then the array name and the element index inside parentheses.
TempVariable = Month(1)
The code above uses the array from the months example. The value of the second array
element is copied into a scalar variable. The value is then logged:
LogMessage(TempVariable)
To use the value of an array element in a function or target field expression, simply list the
array name and the element index. In the months example, you can rewrite the values
without the intermediate variable, like so:
LogMessage(Month(1))
Arrays with two dimensions can be used to store multiple fields and multiple records.
When used in combination with event-condition-action rules, arrays become powerful
tools to store summary data, such as number of records output by record type and errors
per field.
Adding Variables
Declare variables from the Process window or the Map window. Public variables with the
variant data type appear in the Configuration dialog. However, if you later change the
266
Variables
initial value or delete one of these variables from the Process window or the Map window,
the changes are not updated in the Configuration dialog.
Note You can also declare variables with scripting. Use the Dim keyword to declare a local
variable. Scope variables with the Public and Private keywords.
>> To add a variable
1
From the View menu in the Process window or Map window, select Globals.
2
In the Globals dialog, select the Variables tab.
3
Click the Add a variable icon.
4
Enter a unique name for the variable, then select a type.
5
Add a description, if desired.
6
Enter the necessary information and save your changes.
Option
Description
Variable name
Meaningful name for the variable.
Variable type
Available types:
• Variant
• DJImport
• DJExport
• DJRecord
• DJField
• DJRowSet
• DJMessage
• DJComponent
• JavaObject
• JavaVW
• Object
• DOMDocument
• DOMNode
Public
Select to make the variable public. The default setting is off (private).
Note: For variables of the variant data type, you must select Public for the variable to
appear in the configuration.
267
Option
Description
Array
Select if the variable is an array. Available only for the variant data type.
Dimension
Enter the dimension of the array. To add another dimension, click Add dimension. For
more information, see Dimensions of Variables.
Lower Bound
Lower bound for each dimension of an array variable.
Upper Bound
Upper bound for each dimension of an array.
Initial Value
Initial value for the variable. Available only for variants.
See Also
Importing Variables
Run-Time Configurations
For DJMessage examples, search for “DJmessage variables” in the documentation.
Scoping Variables
Guidelines for Naming Variables
Variant Data Type
Dimensions of Variables
Clearing Variables and Array Elements
Importing Variables
Import an existing variable to a map or process to save time. Importing a variable adds the
variable to the global variable list for the current artifact. This public variable is declared
and instantiated, so that you do not need to do this in the code.
After you importing, you can edit the variable if desired.
>> To import an existing variable
1
From the View menu in the Process window or Map window, select Globals.
2
In the Globals dialog, select the Variables tab.
3
Click the Import variable icon.
4
In the Import Variables dialog, select the map or process that contains the variable to
import.
5
Select the variable to import or click the Select all variables icon.
268
Variables
6
Make any desired edits to the variables you are importing.
7
Click Import.
Note If you attempt to use an unavailable variable when scripting, an undefined variable error
appears. Ensure the variable exists and then import it into your map or process.
See Also
Adding Variables
Run-Time Configurations
For DJMessage examples, search for “DJmessage variables” in the documentation.
Scoping Variables
Guidelines for Naming Variables
Variant Data Type
Dimensions of Variables
Clearing Variables and Array Elements
Clearing Variables and Array Elements
Clear any declared object variable or array element containing objects as soon as it is no
longer needed. An uncleared variable can decrease performance by absorbing valuable
resources on the system, long after its usefulness has ended.
A handy place to clear public variables is the Stop step in the Process window. If the
variable is used for only a few steps in a large process, use a Script step to clear the variable
right after the last step that requires it.
Local variables are automatically released when the function in which they were defined
exits. Private variables are released when the transformation is complete.
Examples of Clearing Variables and Elements
The following example shows how to clear an object variable:
Set variablename = Nothing
The following example shows how to clear an array element:
MyArray(0) = Null
The following example shows how to clear an array element using the Null function:
269
MyArray(1) = Null()
The following example shows how to clear all array elements simultaneously by looping
through the array. The array was initialized to contain 100 elements:
Dim i
For i = 0 to 99
MyArray(i) = Null
Next i
Note that element values can be saved by using the Preserve keyword.
Caution An array is destroyed then recreated when the ReDim statement is used to resize
it. Excessive use of ReDim may fragment memory and decrease performance. See ReDim
Statement.
See Also
Scoping Variables
Guidelines for Naming Variables
Variant Data Type
Dimensions of Variables
Adding Variables
270
Objects
Objects
This section includes information on the objects available in the scripting language. Any
applicable exceptions are noted with the appropriate topics.
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Object Variables
Object Operators
Object Properties
DJRecord Object Type
DJField Object Type
DJImport and DJExport Object Types
DJRowSet Object Type
DOMDocument Object Type
DOMNode Object Type
DJComponent Object Type
DJMessage Object Type
Using DJMessage and DJComponent Objects in Expressions
Java and Data Types
Java Class Objects and Scripts
Transformation Object
Project Object
Object Variables
You can use object variables in expressions. An ordinary variable can be thought of as a
name for a location in the computer's memory that holds data. An object variable is a
name for a location in the computer's memory that holds a reference (or pointer) to an
object.
To use object variables in the Map window, declare and instantiate an object (as in the
BeforeTransformation event handler). Then, create a reference to the object.
Use the NEW keyword with internal objects (DJIMPORT, DJEXPORT, DJFIELD, DJRECORD).
Use the CreateObject and GetObject functions with external objects (COM/Automation/
OLE/ActiveX):
Set MyObject = New DJIMPORT "Access 97"
Set MyObject = CreateObject ("Excel.Application")
273
Note Connector name, in this case "Access 97", must be exactly the same as it is listed in the
Map window. For example, typing "Access" does not work.
Use the object, then release it by using the AfterTransformation event handler:
Set MyObject = Nothing
Note For object variables only (not for ordinary scalar variables, nor arrays): Clear the
reference to the object using the SET and NOTHING keywords.
See Also
For information on clearing object variables, search for “clearing variables” in the
documentation.
Declaring Object Variables
Example 1
This example declares the variable F as a djfield type of transformation wide object
variable.
private F as djfield
Example 2
This example declares the variable F as a djfield type of a local object variable.
dim F as djfield
Assigning a value to an object variable must be done using the SET operator. Assignment
is the only action you can take with an object variable alone. If you want to do something
else with the object, use one of the object properties listed below.
Example 3
This example assigns the object variable F to be a pointer to the default field (generally the
first field in a source file).
set F = FieldAt("/SOURCE/R1/MyField")
274
Objects
Internal Object Variables for Mapping
The internal object variables available in the Map window include: djimport, djexport,
djrecord, djfield, err, and sys. You must declare object variables before you set them.
However, you cannot set the err and sys variables.
Note For the object properties you can use with these variables, see Object Properties.
Name
Description
djimport
Source type or source connector. This must be set to one of the entries on the source
connlist, exactly (case sensitive) as shown in the Map window. The default property for
djimport is NAME.
djexport
Target type or target connector. This must be set to one of the entries on the target connlist,
exactly (case sensitive) as shown in the Map window. The default property for djexport is
NAME.
djrecord
Record type. This must be set to one of the record type names that you have defined within
the Map window. The default property for djrecord is NAME.
djrowset
Container for storing collections of record instances. Using this object is more convenient
for storing record images than arrays.
djfield
Field name. This must be set to a specific field in the source or target table. The default
property for djfield is VALUE.
err
Most recent error encountered in the expression process. The default property is the error
code from the last error.
sys
System object. You can use the System keyword to make global changes. There is no default
property for sys. See Retrieve and Set LogFile and LogMask Properties.
Example Using the DJField Object Variable
Place this expression in an Execute action at the BeforeTransformation event.
private x as djfield
set x = FieldAt("/SOURCE/R1/MyField")
x.value
This returns the data in the default (usually first) source field.
Note Mapping does not support object variable arrays.
275
See Also
Search for “ActiveX” in the documentation.
Scoping Variables
Err Object Variable
The Err object variable contains a reference to a system object used to provide information
on integration scripting language exceptions.
The Err object properties are accessed in the same way as with Visual Basic. Err.Number is
the error number; Err.Description is the error description, and so on. These properties are
read-only.
Property
Type
Access
Description
Number
Integer
RO
Error code from the last error (default property).
Description
String
RO
String describing last error.
Source
String
RO
Name of integration language source code module where error
occurred.
Line
Integer
RO
Line number in source code where the error occurred.
StackTrace
String
RO
String with a stack trace showing the stack frames from when
the error occurred.
Many run-time errors are trappable using run-time error trapping statements, such as On
Error GoTo Statement. To find out what error was trapped, use the Err object. Err object
properties are reset every time a run-time error trapping statement is executed.
Example
This example illustrates the use of the Err object. When code in the StackTrace.ezscript file
is executed, the following appears:
Error 114
DivideByZero(StackTrace.ezscript:2)
‘The code for StackTrace.ezscript. Define a function that returns a
Divide By Zero exception:
function DivideByZero(a)
return a / 0
end function
276
Objects
' Define a function to call DivideByZero, trap the exception, and
print a stack trace:
function test()
On Error Goto err_Test
return DivideByZero(10)
err_Test:
Print("Error " & err.Number)
Print(err.StackTrace)
end function
' Execute the function test()
test()
Object Operators
The following table details object operators, their options, and examples of usage.
Name
Description and Example
NEW
Specifically for connector object variables (djimport and djexport). NEW indicates that a
new object is being created, as opposed to assigning a reference to an existing object. The
only parameter required is the name (connlist entry) of the connector being created.
Example of assigning a reference to an existing object:
MyImport = MyOldImport
Example of the NEW operator:
set MyImport = new djimport "Microsoft SQL Server 7"
SET
Operator used to assign an object to a previously dimensioned object variable
Example:
dim x as djfield
set x = FieldAt("/SOURCE/R1/MyField")
277
Name
Description and Example
=
The assignment operator. This is only used in the context of the SET operator to assign an
object address to a variable name. It cannot be used for comparison.
Example:
set x = FieldAt("/SOURCE/R1/MyField")
This would be read as "Set X" to the default field, not as "Set X" equals the default field.
IS NOTHING
Checks if an object variable has been dimensioned and set. Returns 0 if the object exists,
and has been set, 1 otherwise.
Example:
if X is nothing then
dim X as djfield
set X = FieldAt("/SOURCE/R1/MyField")
Object Properties
Several object properties are available for you to use. These properties are useful in
different ways depending on the object they are associated with. Properties are always
connected with a dot to the object variables they affect.
variable.typename
In general, object variables are always associated with properties when they are used in
expressions. Declaring and assigning are the only actions taken on an object variable itself.
If an object variable is used in an expression without a property, the default property is
evaluated.
Example
Because Value is the default property for djfield type variables, this example evaluates the
value of the data in the default field to see if it is greater than 4.
dim F as djfield
set F = FieldAt("/SOURCE/R1/0")
F > 4
Just as if you had written:
dim F as djfield
set F = FieldAt("/SOURCE/R1/0")
F.value > 4
278
Objects
Read Write Abilities of Object Properties
Some of the properties can be both read from and written to. Others can only be read or
only written. In some cases, it depends on the object they are associated with. (The
connector objects are DJImport and DJExport.)
RO = Read Only
WO = Write Only
RW = Read Write
See Also
Search for “ActiveX” in the documentation.
Scoping Variables
CreateObject Function
GetObject Function
DJRecord Object Type
The DJRecord object is a container for field instances. The DJRecord and DJField objects
that the object contains represent a record layout (schema). DJField objects can also serve
as data containers for a record instance.
Property
Type
Access
Description
Fields Property
DJField
RO
Get a reference to a field in a record layout by name or
ordinal position.
FieldCount Property
Integer
RO
Return the number of fields in the record object.
Name Property
String
RW
Get/set the name of the DJRecord object.
Self Property
DJRecord
RO
Return a reference to the object itself.
Method
Type
Description
Copy Method
--
Copy the field contents from another record object. The clear flag
indicates whether the target fields are cleared before doing the copy
operation.
279
Copy Method
--
Copy the contents of a DJRowSet record or another DJRecord object to a
record layout of a DJRecord object. The clear flag indicates whether the
target fields are cleared before doing the copy operation.
NewField Method
DJField
Append a new field to the record object. If a field reference is provided
(fld), it is used as a template for data type.
Operator
Type
Description
New
DJRecord
Create a new object
Properties
FieldCount Property
The FieldCount property returns an integer value with the number of fields in the record
layout for a DJRecord object.
Syntax
record.FieldCount
Type
Required
Description
DJRecord
Yes
Reference to the DJRecord, which is the subject of the property or method
invocation.
Example
The following example prints the names of each field in a DJRecord object named r.
For i=1 To r.FieldCount
Print("Field name " & i & ": " & r.Field(i).Name)
Next i
Fields Property
The Fields property is a container for the fields in a record layout. The property is indexed
by field name or by ordinal position in the record layout.
Syntax
record.Fields(n)
280
Objects
Type
Required
Description
DJRecord
Yes
Reference to the DJRecord, which is the subject of the property or method
invocation.
Integer or String
Yes
An expression that evaluates to a string, with the name of the field or an
Integer with the position of the field in the container.
Example
Get a reference to the third field in the default record layout of the myImport DJImport
object.
Dim f As DJField
Dim r As DJRecord
Set r = myImport.Records(1)
Set f = r.Fields(3)
Name Property
The Name property accesses the record type name for a DJRecord object. It is an alias for
the Value property.
Syntax
record.Name
Type
Required
Description
DJRecord
Yes
Reference to the DJRecord, which is the subject of the property or method
invocation.
Example
Set the record type name for a new DJRecord object.
Dim r As DJRecord
Set r = New DJRecord
r.Name = "Detail"
Self Property
The Self property is used for getting a reference to an object that can then be passed as an
argument to a function or method call. The reason for having a special property for getting
281
the object reference is to resolve an ambiguity with the default property Name. This is
similar to the distinction between normal variable assignment (Let) the use of Set for
assigning object variables.
When you use a DJRecord object variable without an associated property or method, the
integration language processor assumes an implied access of the Name property.
Syntax
record.Self
Type
Required
Description
DJRecord
Yes
Reference to the DJRecord, which is the subject of the
property or method invocation.
Example
The following example shows how to use the Self property for copying the contents of a
DJRecord object r to the first record layout of the primary target for the map.
RecordAt("SOURCE/R1").Copy(r.self)
Methods
Copy Method
The Copy method is used to copy data from one DJRecord object to another DJRecord
object or from a record in a DJRowSet to a DJRecord object. The data is copied field by
field. If the source of the copy has more fields than the target, the copy will stop after data
is copied to the last field in the target. Similarly, if the source has fewer fields than the
target, the copy will stop after copying the last source field.
The clear parameter can be used to clear the target fields of data before the copy
operation. The fields are cleared by initializing them with null values. This is useful for
cases where the source records may have fewer fields than the target, and it is necessary
to make sure that none of the old field values remain.
Syntax
record.Copy(rec, [, clear])
OR
record.Copy(rs, n [, clear])
282
Objects
Type
Required
Description
DJRecord
Yes
Reference to the DJRecord, which is the subject of
the property or method invocation.
DJRecord
Yes
Reference to a DJRecord object to be used as the
source for the copy.
DJRowSet
Yes
Reference to a DJRowSet.
Integer
Yes
Index of the record in the DJRowSet collection to be
used as the source for the copy.
Boolean
No
Flag indicating whether or not the target record
contents should be cleared before the copy
operation.
Exceptions
The Copy method may return one of the following exceptions if there is an error at run
time.
Exception
Description
ERR_TYPEMISMATCH
Returned if any of the arguments for the method are
invalid.
Example
The follow code snippet copies field values from the source record called 1 to the first
target record type:
RecordAt("/SOURCE/1").Copy(RecordAt("/SOURCE/1").self)
NewField Method
The NewField method allows you to append a new field to the end of the record layout for
a DJRecord object.
When the NewField method is called without the optional field argument, a new Text field
with a length of 16 characters are appended to the end of the record layout. The length of
the Text field can be changed using the Length property of the DJField object interface.
When the optional field argument is provided, it is used as a template for creating the new
field. The new field is created using all of the data type information from the template.
Record and field metadata, such as the field name, will not be cloned.
The NewField method returns a reference to the new DJField object.
283
Syntax
record.NewField([field])
Type
Required
Description
DJRecord
Yes
Reference to the DJRecord, the subject of the property or method
invocation.
DJField
No
Reference to a DJField object used as a template for field data type
information.
Exceptions
The NewField method may return one of the following exceptions if there is an error at run
time.
Exception
Description
ERR_OBJREQ
Returned if optional field parameter is not a reference to a valid DJField
object.
ERR_OUTOFMEM
Returned when there is not enough memory to create a new DJField
object.
ERR_ROOBJECT
Returned when there is an attempt to add a field to a read-only object.
Example
The following example shows how to create new DJField objects for a record layout using
NewField.
Append a field to the default record object:
Dim r As DJRecord
Set r = New DJRecord
Dim fld As DJField
Set fld = r.NewField()
Change the length of the field to 64 characters:
fld.Length = 64
fld.Name = "MyNewField"
284
Objects
Operators
New Operator
The New operator creates a new instance of a DJRecord object.
The operator returns a reference to the new object. Typically, this reference is assigned to
an object variable that has been declared with a compatible type. The assignment is done
using the Set statement.
Syntax
New DJRecord
Example
The following example shows how to create a new DJRecord.
Public r As DJRecord
Set r = New DJRecord
See Also
Using DJRecord and DJField Objects to Access Metadata
DJField Object Type
The DJField object type is used to access field level properties for a record layout. It is
typically used in conjunction with objects of type DJRecord Object Type.
It is impossible to create an independent DJField object, since there is no New operator
defined for the type. However, it is possible create new DJField objects for DJRecord
objects using the NewField method.
Properties
Property
Type
Access
Description
Length
Property
Integer
RW
Get or set the field length.
Name
Property
String
RW
Get or set the field name.
Self
Property
DJField
RO
Return a reference to the object itself.
285
TypeName
Property
String
RO
Get the field type name.
Value
Property
Variant
RW
Get the field value (default property).
ValueCount
Property
Integer
RO
Get the number of values a field contains. Use with arrayed fields
in connectors.
MaxOccurs
Property
Integer
RW
Get or set the maximum number of values a field can contain. Use
with arrayed fields in connectors.
Length Property
Use the Length property to get or set the field length. This table outlines the available
parameters.
Syntax
fld.Length
OR
fld.Length = size
Type
Required
Description
DJField
Yes
Reference to the DJField that is the subject of the property or method
invocation.
Integer
Yes
Integer expression representing the size to assign to the DJField object.
The Length property is not meaningful for all field types. Fields using some of the numeric
data types have predetermined lengths. Attempts to change these are ignored.
The default length for new text fields is 16 characters.
Example
This example shows how to change the field length for a new DJField object. The DJField
object is created in the default record layout for a DJExport object called myexport using
the NewField method.
Dim fld As DJField
fld = myexport.NewField
' Change the length of the field to 64 characters
fld.Length = 64
286
Objects
Name Property
Use the Name property to get or set the name of a DJField object. This table outlines the
available parameters.
Syntax
fld.Name
OR
fld.Name = name
Type
Required
Description
DJField
Yes
Reference to the DJField that is the subject of the property or method
invocation.
String
Yes
String expression representing the name to assign to the DJField object.
Example
The following example shows how to create and name a new DJField object. The DJField
object is created in the default record layout for a DJExport object called myexport using
the NewField method.
Dim fld As DJField
fld = myexport.NewField
fld.Name = "Amount"
Self Property
Use the Self property to get a reference to an object through a variable. The property is
useful when there is ambiguity between the use of the variable name as the object
reference and the use of the variable name as a reference to the default property for the
object.
Syntax
fld.Self
Type
Required
Description
DJField
Yes
Reference to the DJField, which is the subject of the property or method
invocation.
287
Example
The following example shows how to use the Self property to pass a reference to the
object as an argument to a function that expects a DJField reference as input.
Function RefTest(f As DJField)
Print("The field name is " & f.Name)
End Function
Dim fld As DJField
fld = myexport.NewField
fld.Name = "Amount"
RefTest(f.Self)
TypeName Property
Use the TypeName property to get the field type name for a DJField object. This table
outlines the available parameter.
Syntax
fld.TypeName
Type
Required
Description
DJField
Yes
Reference to the DJField, which is the subject
of the property or method invocation.
Example
The following example prints the field type name to the console.
Print(fld.TypeName)
Value Property
Use the Value property to get or set the field data value. When assigning a value to a
DJField object, the value is coerced to a type that is compatible with the field type. For
example, if you assign a Date value to a Text field the Date value is formatted as a string
and the string value is assigned to the field. The Value property is the default property for
the DJField interface.
Syntax
fld.Value
288
Objects
OR
fld.Value = value
Type
Required
Description
DJField
Yes
Reference to the DJField, which is the subject of the property or
method invocation.
Variant
Yes
Expression that evaluates to the value to assign to the DJField
object.
Example
The following example shows how to assign a value to a DJField object. A value of 10019
is assigned to a field called Account, which is a member of the default record layout for the
DJExport object myexport.
myexport.FieldAt("/SOURCE/R1/Account").Value = 10019
Here is an example using the DJField and DJExport objects. This block sets the two objects,
the connector name, and describes the field properties: separator and delimiter:
Dim MyExport As DJExport
Dim MyField As DJField
Set MyExport = New DJExport "ConnectorName"
MyExport.Properties("FieldSeparator") = ","
MyExport.Properties("FieldStartDelimiter") = Chr(34)
MyExport.Properties("FieldEndDelimiter") = Chr(34)
The next three blocks assign field names, set field sizes, and the full path of the target
connect string:
Set MyField = MyExport.NewField
MyField.Name = "Amount"
MyField.Length = 64
Set MyField = MyExport.NewField
MyField.Name = "Field2"
MyField.Length = 255
MyExport.ConnectString="File=C:\path\filename.txt"
289
This block populates "Amount" and "Field2", and includes an alternate method (see line
three). The last line in this block writes to values to the target:
MyExport.FieldAt("/SOURCE/R1/Amount") = FieldAt("/SOURCE/R1/
Field1")
MyExport.FieldAt(/SOURCE/R1/Field2) = FieldAt("/SOURCE/R1/Total")
'The above could also be MyExport.FieldAt("/SOURCE/R1/2") =
FieldAt("/SOURCE/R1/Total")
MyExport.PutRecord
It is important to clear the object once it is no longer needed. Clearing the object releases
the memory location it occupies. Setting the objects to "Nothing", a reserved word, clears
the object and releases the memory location.
Set MyField = Nothing
Set MyExport = Nothing
ValueCount Property
The ValueCount property is helpful when you have a connector that has more than one
value per field. It allows you to use an index to get the number of values a field can contain.
Syntax
fld.ValueCount
Type
Required
Description
DJField
Yes
Reference to the DJField, which is the subject of the property or method
invocation.
Example
This example shows how to retrieve the number of values the field can contain:
DJRecord rec
= new DJRecord;
DJField field = rec.NewField();
field.ValueCount
MaxOccurs Property
The MaxOccurs property supports the use of hierarchical connectors. The property allows
you to use an index to set the maximum number of values a field can contain.
290
Objects
Syntax
fld.MaxOccurs = number
OR
a = fld.MaxOccurs
Type
Required
Description
DJField
Yes
Reference to the DJField, which is the subject of the property or method
invocation.
Example
When setting the array values of a field, make sure to set MaxOccurs to a number equal or
greater than the number of fields you are trying to set. This example sets the field to allow
up to 10 values:
DJRecord rec
= new DJRecord;
DJField field = rec.NewField();
rec.field.MaxOccurs = 10
for i = 1 to 10
rec.field.Value(i) = 100 + i
next i
See Also
Using DJRecord and DJField Objects to Access Metadata
DJImport and DJExport Object Types
DJExport and DJImport are types of objects designed to provide generic interfaces to the
data connectors. These objects can be used to read or write data using the data connectors
or they can be used to manipulate some of the connector metadata.
Note The DJImport object returns a result record set. The DJImport object cannot be used to
execute a general SQL statement.
291
Properties
Property
Type
Access
Description
AtEOF Property
Boolean
RO
Indicate whether or not a DJImport object is at
the end of file.
ConnectString
Property
String
RW
Set/get the connection string for the DJExport
or DJImport object.
CurrentRecordType
Property
Integer
RO
Get the record type index of the last record
read or written.
Database Property
String
RO
Get the database name component of the
connection string.
Encoding Property
Integer
RO
Get the character set encoding number used
by the DJExport or DJImport object.
FieldCount Property
Integer
RO
Get the number of fields in the default record
layout.
Field Property
DJField
RO
Get a reference to a field by name or by ordinal
position.
FileName Property
String
RO
Get the file name component of the
connection string.
Name Property
String
RW
Get/set the target file/table name.
Properties Property
String
RW
Get/set a named adaptor property.
RecordNumber
Property
Long
RW
Get/set the current record number for a
DJImport object.
Record Property
DJRecord
RO
Get a reference to a record layout by name or
by ordinal position.
Self Property
DJExport or
DJImport
RO
Return a reference to the object itself.
Server Property
String
RO
Get the server name component of the
connection string.
SQLStatement
Property
String
WO
Set the SQL statement for a DJImport object.
Table Property
String
RO
Get the table name component of the
connection string.
292
Objects
Property
Type
Access
Description
TypeName Property
String
RO
Get the adaptor type name.
UserName Property
String
RO
Get the user name component of the
connection string.
Value Property
String
RO
Get the adaptor type name (default property).
Operator
Type
Description
New Operator
DJExport or DJImport
Create a new object.
AtEOF Property
Determine whether or not the adaptor for a DJImport object is positioned at the end of
file.
The AtEOF property always returns False when used with the DJExport object.
Syntax
imp.AtEOF
Type
Required
Description
DJImport
Yes
Reference to the DJImport which is the subject of the property or
method invocation.
Example
The following example demonstrates the use of AtEOF as a condition for an If statement.
If imp.AtEOF Then
Set imp = Nothing
End If
ConnectString Property
Get or set the connection string for a DJExport or DJImport object. The connection string
is a set of semicolon separated attribute-value pairs that specify all the information the
DJExport or DJImport object needs to establish a connection with the data source. The
following attributes are supported for the DJImport and DJExport connection strings.
293
Attribute
Description
DATABASE
Database name. This attribute is used for database management types of data sources.
EXTRA
Attribute for specifying adaptor specific connection information. This is sometimes used
for data access middleware such as ODBC or OLE DB.
FILE
Name of a file or URI for the data source. This attribute is used for file oriented data
sources.
FILENAME
A synonym for FILE.
PASSWORD
Password used for authentication with the security system for the data source.
SERVER
Name of a database server. This attribute is primarily with server based database
management systems.
TABLE
Table name. This attribute is typically used with relational database management
systems or with partitioned data sources, such as spreadsheets.
USERID
User name used for authentication with the security system for the data source.
USERNAME
Synonym for USERID.
The DJExport and DJImport connection strings use a subset of the connection strings
supported by DJEngine. DJEngine has more elaborate quoting and escaping mechanisms
for connection strings as well as support for the specification of adaptor properties.
Syntax
impexp.ConnectString
OR
impexp.ConnectString = connection_string
Type
Required
Description
DJExport or DJImport
Yes
Reference to the DJExport or DJImport that is the subject of
the property or method invocation.
String
Yes
Expression that evaluates to a character string with
connection information.
Exceptions
ConnectString returns exceptions if there is an error.
294
Objects
Exception
Description
ERR_TYPEMISMATCH
Returned if the connection string is invalid.
ERR_PROPASSGN
Returned when an error is returned from the adaptor.
Example
The following example shows a simple connection string for connecting to a file oriented
data source and for an Oracle data source
imp.ConnectString = "FILE=tutor1.asc"
imp.ConnectString = "server=test;database=ORCL; _
username=scott;password=tiger;table=emp"
CurrentRecordType Property
Get the record type index of the last record read or written. The CurrentRecordType
property returns an integer index that can be used with the RecordAt property to get a
reference to the Record object for the current record type.
Syntax
impexp.CurrentRecordType
Type
Required
Description
DJExport or DJImport
Yes
Reference to the DJExport or DJImport that is the
subject of the property or method invocation.
Example
The following example prints the name of the current record type for a DJImport object
called myImport to the console.
Print(myImport.Records(myImport.CurrentRecordType).Name)
Database Property
Use the Database Property to get the database name component of the connection string.
Use when a DJImport or DJExport object when these objects are used with data adaptors
that use database names for connecting to a data source.
Syntax
impexp.Database
295
Type
Required
Description
DJExport or DJImport
Yes
Reference to the DJExport or DJImport that is
the subject of the property or method
invocation.
Example
The following example prints the name of the database for the map source.
Print(Database)
Encoding Property
Get the character set encoding number used by the data adaptor for the DJExport or
DJImport object.
The Encoding property returns the numeric code used to represent a character set. For
data adaptors that support Unicode, the number will correspond to the setting of
Properties("Encoding"). The Properties("Encoding") property can be used to get or set the
encoding by name (Unicode-supported adaptors only).
For non-Unicode data adapters, the return value is ENC_OEM.
Syntax
impexp.Encoding
Type
Required
Description
DJExport or DJImport
Yes
Reference to the DJExport or DJImport that is
the subject of the property or method
invocation.
Example
The following example tests the DJImport object, imp, to see if it is using UTF-8 encoding.
If imp.Encoding = ENC_UTF8 Then
Print("Encoding is UTF8")
End If
296
Objects
FieldCount Property
The FieldCount property returns an integer value with the number of fields in the default
record layout for the DJExport or DJImport object. The default record layout is the first
record layout in the RecordAt container.
Syntax
impexp.FieldCount
Type
Required
Description
DJExport or DJImport
Yes
Reference to the DJExport or DJImport that is the
subject of the property or method invocation.
Example
The following example prints the names of each field in the default record layout for the
DJImport object myImport.
For i=1 To myImport.FieldCount
Print("Field name " & i & ": " &
myImport.Field(i).Name)
Next i
Field Property
Get a reference to a field in the default record layout by name. The Field property is a
container for the fields in the default record layout. The property is indexed by field name
in the record layout. The default record layout is the first record in the Records container.
Fields for record layouts other than the default layout can be accessed indirectly through
the Records property.
Syntax
impexp.Field(n)
Type
Required
Description
DJExport or DJImport
Yes
Reference to the DJExport or DJImport that is the
subject of the property or method invocation.
Integer or String
Yes
Expression that evaluates to a string with the
name of the field or an integer with the position
of the field in the container.
297
Example
Get a reference to the third field in the default record layout of the myImport DJImport
object.
Dim f As DJField
Set f = myImport.Field(3)
FileName Property
Use the FileName property to get the name of the file name used by a DJImport or
DJExport object when these objects are used with data adapters that use file oriented or
URI based data access.
Syntax
impexp.FileName
Type
Required
Description
DJExport or DJImport
Yes
Reference to the DJExport or DJImport
that is the subject of the property or
method invocation.
Example
The following example prints the file name for the primary target of a transformation.
Print(FileName)
Name Property
Use the Name property to get either the file name or table name of the connection string
for a DJExport or DJImport object. The name that is returned is the one that is most
appropriate for the adapter type.
Syntax
impexp.Name
298
Type
Required
Description
DJExport or DJImport
Yes
Reference to the DJExport or DJImport
that is the subject of the property or
method invocation.
Objects
Example
The following example prints the file name or table name for the DJExport object,
myExport.
Print(myExport.Name)
Properties Property
Get or set an adapter property. The Properties property is a collection of property values
for the DJExport or DJImport adapter. Property values are strings and the array of
properties is indexed using the adapter property name. The set of properties is adapter
dependent.
Syntax
impexp.Properties(name)
OR
impexp.Properties(name) = value
Type
Required
Description
DJExport or DJImport
Yes
Reference to the DJExport or DJImport that is the
subject of the property or method invocation.
String
Yes
Name of the adapter property to get or set.
String
Yes
Expression that evaluates to a string that is used to
set the property value.
Exceptions
Properties returns exceptions if there is an error.
Exception
Description
ERR_TYPEMISMATCH
Returned if the property name is invalid or if there is an error setting the
specified property.
Example
The following example shows how to enable the header record feature of the ASCII
(Delimited) adapter.
Dim myexport As DJExport
Set myexport = New DJExport "ASCII (Delimited)"
299
myexport.Properties("Header") = "true"
RecordNumber Property
The RecordNumber property is used to set or get the current record number for a
DJImport object. Use the RecordNumber property to control the position of the adapter in
the data source. When RecordNumber is changed, the adapter uses the current record
number to read the data from the data source. The data from the source record is parsed
and the contents moved to the field objects in the record layout. For adapters that support
multiple record layouts, the rules from the schema for the DJImport object is used to
determine the record type. The data is moved to the field objects for the appropriate
record layout and the contents of the CurrentRecordType property is changed accordingly.
RecordNumber can be used to provide either sequential or direct access to records. For
adapters that do not support direct access, direct access is emulated if necessary.
Syntax
imp.RecordNumber
Type
Required
Description
DJExport or DJImport
Yes
Reference to the DJExport or DJImport that is the
subject of the property or method invocation.
Exceptions
RecordNumber returns exceptions if there is an error or if the end of file condition is
detected. The following exceptions can be returned.
Exception
Description
ERR_TYPEMISMATCH
Returned if the record number is less than 1 or if the property is called
with a DJExport object.
ERR_EOF
Returned when the record number causes an attempt to read past the
end of the data source.
ERR_PROPASSGN
Returned when an error is returned from the adapter.
Example
The following code uses the RecordNumber property to get an estimate of the number of
records in the data source associated with the DJImport object imp.
Dim i
300
Objects
On Error Resume Next
For i = 1 to 1000 Step 10
imp.RecordNumber = i
If Err = ERR_EOF Exit For
Next i
If i > 1000 Then
Print(imp.Name & " has more than 1000 records")
Else
Print(imp.Name & " has approximately " & i & " records")
End If
Record Property
The Record property provides access to the list of record layouts from the schema for the
DJExport or DJImport object. The collection can be indexed either by number or by the
record layout name.
Syntax
impexp.Record(n)
Type
Required
Description
DJExport or DJImport
Yes
Reference to the DJExport or DJImport that is the
subject of the property or method invocation.
Integer or String
Yes
Expression that evaluates to a record layout number
or to a record layout name.
Example
The following code snippet prints the field count for the second record layout of the
DJImport object imp.
Print("The second record layout has " _
& imp.Record2.FieldCount & " fields")
Self Property
Use the Self property for getting a reference to an object that can then be passed as an
argument to a function or method call. The reason for having a special property for getting
301
the object reference is to resolve an ambiguity with the default property, Value. This is
similar to the distinction between normal variable assignment (Let) the use of Set for
assigning object variables.
When a DJExport or DJImport object variable is used without an associated property or
method, the integration language processor assumes an implied access of the Value
property.
Syntax
impexp.Self
Type
Required
Description
DJExport or DJImport
Yes
Reference to the DJExport or DJImport that is the
subject of the property or method invocation.
Example
The following shows how to use the Self property for passing a reference to a DJImport
object to the ILBuild function.
' Create a new DJImport object using the SQL Server adapter
Dim imp as DJImport
Set imp = new DJImport("SQL Server")
' Specify the SQL Server connection information
imp.connectstring="database=pubs;username=sa"
' Build the incore table from the result of a SQL query
ILBuild("publishers", imp.self, _
"select prod_id, name from publishers", "pub_id",
"pub_name")
Server Property
Use the Server property to get the name of the server used by a DJImport or DJExport
object when these objects are used with data adapters that are clients to server-based
storage management systems.
Syntax
impexp.Server
302
Objects
Type
Required
Description
DJExport or DJImport
Yes
Reference to the DJExport or DJImport that is the
subject of the property or method invocation.
Example
The following example prints the name of the server used for the map source.
Print(Server)
SQLStatement Property
Set the SQL statement to be used by a DJImport object for querying a SQL data source.
Syntax
imp.SQLStatement
Type
Required
Description
DJImport
Yes
Reference to the DJImport that is the subject of the property or
method invocation.
Remarks
When you use a DJImport object with one of the SQL adapters, you have the option of
specifying a table name or a SQL statement for accessing data. When you use a table
name, the SQL adapter generates a simple SQL SELECT statement to return all columns and
all rows in the table.
The SQLStatement property provides greater flexibility by allowing you to execute any SQL
statement that returns a row set. This includes the execution of queries that use filtering,
ordering, grouping, or joins and stored procedures.
The SQL statement should be executable with no side effects. It is possible that the SQL
statement may be executed multiple times if the SQL adapter needs to emulate direct
access.
Frequent execution of SQL statements can cause performance problems. Execution of the
SQL statement occurs when the SQLStatement property is assigned. The execution is
dynamic, so the SQL statement must be compiled and executed by the back end SQL
engine each time. In cases where a row set can be reused, it is best to run the query
outside of loops. This includes implicit loops, such as the transformation loop in a map.
The best way to ensure that the SQL statement is executed once is use a Public variable for
the DJImport object and to perform the query in the BeforeTransformation event of map
303
or in an early step of a process design. The DJImport object can be shared across multiple
steps in a process design if it is declared as a public variable.
The use of the SQLStatement property for table lookups should be limited to cases where
performance is not a concern or the lookups are infrequent. If the lookups are performed
using large tables or complex queries, it is recommended that the queries be optimized
through the use of indexes and precompiled SQL statements. When performance is
important and lookups are frequent, the use of lookup files within maps is recommended.
SQLStatement is a write-only property. The purpose of the property is to affect the
DJImport object by executing a SQL statement and not to provide a place to store the
statement.
Exceptions
SQLStatement returns exceptions if there is an error.
Exception
Description
ERR_TYPEMISMATCH
Returned if property is assigned using a DJExport object or if the adapter
does not support SQL.
ERR_EOF
Returned if the row set returned by the SQL statement is empty.
ERR_PROPASSGN
Returned when an error is returned from the adapter.
Example
This example uses the SQLStatement property to select a set of records.
' Create a new DJImport object using the SQL Server adapter
Dim imp as DJImport
Set imp = new DJImport("SQL Server")
' Specify the SQL Server connection information
imp.connectstring="database=pubs;username=sa"
' Build the incore table from the result of a SQL query
imp.SQLStatement = "select * from publishers"
Table Property
Get the table name component of the connection string. Use the Table property to get the
name of a table used by a DJImport or DJExport object when these objects are used with
304
Objects
data adapters that work with database management systems or for adapters that work
with partitioned file formats.
Syntax
impexp.Table
Type
Required
Description
DJExport or DJImport
Yes
Reference to the DJExport or DJImport that
is the subject of the property or method
invocation.
Example
The following example prints the name of the server used for the map source.
Print(Table)
TypeName Property
Get the adapter type name. The TypeName property returns the adapter name used to
create the DJExport or DJImport object.
Syntax
impexp.TypeName
Required
Description
Yes
Reference to the DJExport or DJImport that is the subject
of the property or method invocation.
UserName Property
The UserName property is used to get the user name (USERNAME or USERID) specified in
the connection string for authentication.
Syntax
impexp.UserName
Type
Required
Description
DJExport or DJImport
Yes
Reference to the DJExport or DJImport that is
the subject of the property or method
invocation.
305
Example
The following example prints the name of the user name used for the map source.
Print(UserName)
Value Property
The Value property returns the adapter name used to create the DJExport or DJImport
object. It returns the same result as the TypeName property.
The Value property is the default property for the DJExport and DJImport objects.
Syntax
impexp.Value
Type
Required
Description
DJExport or DJImport
Yes
Reference to the DJExport or DJImport that is the
subject of the property or method invocation.
Example
Print the adapter name for the DJExport object myExport. It is not necessary to reference
the Value property explicitly, since it is the default property.
Dim myExport As DJExport
Set myExport = New DJExport "XML"
Print(myExport)
Methods
Method
Type
Description
Copy Method
Copy the field contents from another record object. The clear flag
indicates whether the target fields are cleared before doing the copy
operation.
Copy Method
Copy the field contents from the nth row of DJRowSet object rs. The
clear flag indicates whether the target fields are cleared before doing
the copy operation.
NewField Method
PutRecord Method
306
DJField
Append a new field to the DJImport or DJExport object. If a field
reference, fld, is provided, it is used as a template for data type.
Write a record of the specified type to the target.
Objects
Copy Method
The Copy method copies the contents of a DJRowSet record or another DJRecord object to
the default record layout of a DJExport or DJImport object.
The data is copied field by field. If the source of the copy has more fields than the target,
the copy will stop after data is copied to the last field in the target. Similarly, if the source
has fewer fields than the target, the copy will stop after copying the last source field.
The clear parameter can be used to clear the target fields of data before the copy
operation. The fields are cleared by initializing them with null values. This is useful for
cases where the source records may have fewer fields than the target and it is necessary
to make sure that none of the old field values remain.
Syntax
impexp.Copy(rec, [, clear])
OR
impexp.Copy(rs, n [, clear])
Parameters used with the first variant of the method:
Type
Required
Description
DJExport or DJImport
Yes
Reference to the DJExport or DJImport that is the subject
of the property or method invocation.
DJRecord
Yes
Reference to a DJRecord object to be used as the source
for the copy.
Boolean
No
Flag indicating whether or not the target record contents
should be cleared before the copy operation.
Parameters used with the second variant of the method:
Type
Required
Description
DJExport or DJImport
Yes
Reference to the DJExport or DJImport that
is the subject of the property or method
invocation.
DJRowSet
Yes
Reference to a DJRowSet.
307
Integer
Yes
Index of the record in the DJRowSet
collection to be used as the source for the
copy.
Boolean
No
Flag indicating whether or not the target
record contents should be cleared before
the copy operation.
Exceptions
The Copy method may return one of the following exceptions if there is an error at run
time:
Exception
Description
ERR_TYPEMISMATCH
Returned if any of the arguments for the method are
invalid.
Example
The following code snippet copies field values from the first source record type to the first
target record type.
Records(1).Copy(Records(1).self)
NewField Method
Use the NewField method to append a new field to the end of the default record layout
for the DJExport or DJImport object.
When the NewField method is called without the optional field argument, a new Text field
with a length of 16 characters are appended to the end of the record layout. The length of
the Text field can be changed using the Length property of the DJField object interface.
When the optional field argument is provided, it is used as a template for creating the new
field. The new field is created using all of the data type information from the template.
Record and field metadata, such as the field name, will not be cloned.
The NewField method returns a reference to the new DJField object.
Syntax
impexp.NewField([field])
308
Objects
Type
Required
Description
DJExport or DJImport
Yes
Reference to the DJExport or
DJImport that is the subject of the
property or method invocation.
DJField
No
Reference to a DJField object used
as a template for field data type
information.
Exceptions
The NewField method may return one of the following exceptions.
Exception
Description
ERR_OBJREQ
Returned if optional field parameter is not a reference to a
valid DJField object.
ERR_OUTOFMEM
Returned when there is not enough memory to create a
new DJField object.
ERR_ROOBJECT
Returned when there is an attempt to add a field to a readonly object.
Example
The following example shows how to create new DJField objects for a record layout using
NewField.
' Append a field to the default record object
Dim myexport As DJExport
Set myexport = New DJExport "ASCII (Delimited)"
Dim fld As DJField
Set fld = myexport.NewField()
' Change the length of the field to 64 characters
fld.Length = 64
fld.Name = "MyNewField"
FileWrite("The default record has " & myexport.FieldCount
& " fields")
309
PutRecord Method
Use the PutRecord method to put a record of the specified type to the target of a DJExport
object. The PutRecord method outputs a record to the target for a DJExport object. The
record is assembled from the field values stored in the DJField objects for either the
default record layout or for a record layout specified with the type parameter.
Syntax
impexp.PutRecord([type])
Type
Required
Description
DJExport
Yes
Reference to the DJExport that is the subject of the
property or method invocation.
Integer or String
No
Name of a record type or an index into the Records
container of the type of record to write.
Exceptions
The PutRecord method may return one of the following exceptions.
Exception
Description
ERR_ROOBJECT
Returned when there is an attempt to put a record to a read-only DJExport
object.
ERR_TYPEMISMATCH
Returned if the object of the PutRecord operation is not a DJExport object or
if the adapter returns an error during the put.
ERR_RECACCESS
Returned if the type parameter does not match a defined record type.
Example
The following example shows write a record with a single field to a delimited ASCII file.
Dim myexport As DJExport
Set myexport = New DJExport "ASCII (Delimited)"
Dim fld As DJField
Set fld = myexport.NewField()
' Change the length of the field to 64 characters
fld.Length = 64
fld.Value = "This is a test"
310
Objects
myexport.ConnectString = "FILE=test.asc"
myexport.PutRecord()
Operators
New Operator
The New operator creates a new instance of a DJExport or DJImport object. It takes one
parameter, the name of the data access adapter. Once an object is created, the choice of
adapter can not be changed without recreating the object. The names used to create the
objects are the same names used to select source and target adapters in the Map window.
The operator returns a reference to the new object. Typically, this reference is assigned to
an object variable that has been declared with a compatible type. The assignment is done
using the Set statement.
Syntax
New DJExport adaptor_type
OR
New DJImport adaptor_type
Type
Required
Description
String
Yes
Expression that evaluates to a string with the name of
the data adapter to create for the DJExport or DJImport
object.
Exceptions
The New operator returns exceptions if there is an error creating the object.
Exception
Description
ERR_TYPEMISMATCH
Returned if the adapter type name does not match a registered or licensed
adapter type.
ERR_OBJNOTSET
Returned if there is an error creating the adapter instance.
Example
The following example shows how to create a DJExport object with the "XML" adapter and
to assign a reference to the new object to a public variable called myExport:
Public myExport As DJExport
311
Set myExport = New DJExport "XML"
Retrieve and Set LogFile and LogMask Properties
LogFile and LogMask properties allow you to retrieve and set logging and masking for the
System object or individual DJImport / DJExport objects.
For instance, to retrieve the current system (global) logfile use:
System.LogFile
To set the system logfile use:
System.LogFile = "djwin.log"
Similarly in LogMask, you can retrieve the following integer values:
•
•
•
•
•
Info 1
Warn 2
Error 4
Severe 8
Debug 16
To set the log to record only the error and warning messages use:
System.LogMask=6
In addition, these properties can be used in DJImport and DJExport objects . The data
adapters support separate log files. Using the above mentioned properties, you can set the
log file for an individual data connector:
dim sp as djimport
sp.logfile
The above expression returns the log file for the given DJImport object.
Example of DJImport Usage
If you want to check whether or not the DJImport object returned an empty recordset, you
can inspect the AtEOF object property:
Ignore all errors, including "End of File" (119).
On Error Resume Next
Set the SQL statement property to query the DJImport source.
MyLookup.SQLStatement = "SELECT * FROM [Customers] WHERE [State] =
'TX'"
312
Objects
Test if we are at the end of the record set.
If MyLookup.AtEOF = 0 Then
The dynamic SQL lookup was successful; assign the result to this target field.
MyLookup.FieldAt("Customer")
Else
No results were returned. You can reject the record, insert a default value, etc.
"No Match"
End If
Example of DJImport Resultset Looping
Ignore all errors, including "End of File" (119).
On Error Resume Next
Set the SQL statement property to query the DJIMPORT source.
MyLookup.SQLStatement = "SELECT * FROM [Customers] WHERE [State] =
'TX'"
Assume the lookup returns multiple records, so build a loop. Use the AtEOF property as
the condition of evaluating/ repeating the loop.
While MyLookup.AtEOF = 0
Concatenate the value of this record into a temporary string variable. You can also sum
numeric values, use an expression to get the min/max, etc.
strResults = strResults & ", " & MyLookup.Field("Customer")
Move to the next record in the DJImport object by incrementing the RecordNumber
property.
MyLookup.RecordNumber = MyLookup.RecordNumber + 1
Wend
Return the value of the temporary string variable to target field.
strResults
Note This example does not handle expression errors.
313
Example of Trapping Expression Errors
In an error event, type:
On Error GoTo ErrHandler
...
Check the specific error code returned (119 = End of File).
If Err.Number = 119 Then
Ignore End of File errors; continue where we left off.
Resume Next
Else
Handle any other error here.
...
End If
See Also
DJExport Object Type Notes
Search for “dynamic SQL lookups” and “counter variable” in the documentation
DJExport Object Type Notes
The DJExport objects are internal objects designed to provide generic interfaces to
connectors. These objects can be used to read or write data using the data connectors.
They can also be used to manipulate some of the connector metadata.
DJExport is the target type or target connector object variable, and must be set to one of
the entries on the target connector list, exactly (case sensitive) as shown in the Map
window. The default property for djexport is NAME.
For a DJExport properties list, see DJImport and DJExport Object Types.
Limitations
The default size is 16 and cannot be changed.
Example of DJExport Object Type Usage
Enter your DJExport variable in an event:
Private MyExport as DJExport
314
Objects
Set MyExport = New DJExport "ConnectorName"
MyExport.NewField
MyExport.Field(N).Name = "FieldNameN"
MyExport.Properties("Property Name") = "Prop Value"
MyExport.ConnectString = "FileName = path\filename"
MyExport.Field(N) = "Value(N)"
MyExport.PutRecord
Be sure to destroy the object variable after you are finished. To do this, go to the
AfterTransformation event and enter:
Set MyExport = Nothing
See Also
DJRowSet Object Type
DJField Object Type (for an example using both the DJField object and the DJExport object)
Search for “counter variable” in the documentation.
DJRowSet Object Type
The DJRowSet object is container for storing collections of record instances. A single
DJRowSet object can store many different types of records. DJRowSet is both more flexible
and more convenient for storing record images than arrays. Unlike arrays, each row in a
row set can have a different number of elements. In effect, the row set is like a jagged
array. Another advantage of row sets over arrays is that row sets have operations for
inserting, appending, and deleting rows. With arrays, these operations require userdefined code.
The following tables show the properties and methods supported by the DJRowSet object.
Property
Type
Access
Description
FieldCount Property
Integer
RO
Return the number of fields in row rowno.
Self Property
DJRowSet
RO
Return a reference to the row set object.
Size Property
Integer
RO
Return the number of rows in the row set.
TypeName Property
String
RW
Get/set the record type name for the row rowno of the
row set.
Value Property
Variant
RW
Get/set the value for the field fldno of the row rowno
(default).
315
Method
Description
Append Method
Append a new row using the contents of a DJRecord object.
Clear Method
Clear all rows from the row set.
Erase Method
Erase row rowno from the row set.
Insert Method
Insert a new row as row rowno using the list of values. rowno can be any integer
value from 1 through Size + 1.
Operator
Type
Description
New Operator
DJRowSet
Create a new object.
Properties
FieldCount Property
The FieldCount property returns an integer value with the number of fields in specified
row of the row set.
Syntax
rowset.FieldCount(rowno)
Type
Required
Description
DJRowSet
Yes
Reference to the DJRowSet object that is the subject of the
property or method invocation.
Integer
Yes
Index for the row in the row set.
Exceptions
The FieldCount method may return the following exceptions if there is an error at run
time:
Exception
Description
ERR_TYPEMISMATCH
Returned if the row index is invalid.
Example
The following example gets the number of fields for the 3rd record in the row set.
316
Objects
fcnt = rs.FieldCount(3)
Self Property
The Self property is used for getting a reference to an object that can then be passed as an
argument to a function or method call. The reason for having a special property for getting
the object reference is to resolve an ambiguity with the default property, Value. This is
similar to the distinction between normal variable assignment (Let) the use of Set for
assigning object variables.
When a DJRowSet object variable is used without an associated property or method, the
integration language processor assumes an implied access of the Value property.
Syntax
rowset.Self
Type
Required
Description
DJRowSet
Yes
Reference to the DJRowSet object which is the
subject of the property or method invocation.
Example
The following example shows how the Self property might be used when copying data
from a row set to a record. In this example, rec is a DJRecord variable and rs is a DJRowSet
variable. The following would copy the contents of the third row of rs to the fields in rec.
rec.Copy(rs.Self, 3, True)
Size Property
The Size property is used to determine how many rows are stored in a DJRowSet container.
Syntax
rowset.Size
Type
Required
Description
DJRowSet
Yes
Reference to the DJRowSet object that is the
subject of the property or method invocation.
Example
The following example clears the row set, rs, if it contains any rows.
317
If rs.Size > 0 Then rs.Clear
TypeName Property
Get or set the record type name for a row in a row set. The DJRowSet can contain record
images for many different types of records. The TypeName property is used to identify
type of each record.
Syntax
rowset.TypeName(rowno)
OR
rowset.TypeName(rowno) = name
Type
Required
Description
DJRowSet
Yes
Reference to the DJRowSet object which is the subject of the
property or method invocation.
Integer
Yes
Index for the row in the row set.
String
Yes
Record type name.
Exceptions
The TypeName method may return the following exceptions if there is an error at run
time:
Exception
Description
ERR_TYPEMISMATCH
Returned if the row index is invalid.
Example
The following example sets the record type name for the third record in the row set to
"Header".
rs.TypeName(3) = "Header"
Value Property
Get or set the field value for a field in a row stored in a row set.
Syntax
rowset.Value(rowno, fldno)
318
Objects
OR
rowset.Value(rowno, fldno) = value
Type
Required
Description
DJRowSet
Yes
Reference to the DJRowSet object that is the
subject of the property or method invocation.
Integer
Yes
Index for the row in the row set.
Integer
Yes
Index for the field in the selected row.
Variant
Yes
Value to assign to the field.
Exceptions
The Value method may return the following exceptions if there is an error at run time:
Exception
Description
ERR_TYPEMISMATCH
Returned if either the row or field index is
invalid.
Example
The following example sets the value for the tenth field of the second row:
rs.Value(2, 10) = "Row 2, Field 10 data"
Methods
Append Method
The Append method adds a new row to a row set. The new row is created using a list of
values or by copying values from a DJRecord object.
Syntax
rowset.Append(record)
OR
rowset.Append(values)
319
Type
Required
Description
DJRowSet
Yes
Reference to the DJRowSet object that is the
subject of the property or method invocation.
DJRecord
Yes
Reference to the DJRecord used to append a
new row to the row set.
Variant
Yes
Comma-delimited list of values used as field
values for a new row in the row set.
Exceptions
The Append method may return the following exceptions if there is an error at run time.
Exception
Description
ERR_TYPEMISMATCH
Returned if any invalid parameters are passed to the method.
Example
The following example creates a new DJRowSet object and appends a couple of rows.
Dim rs as DJRowSet
Set rs = New DJRowSet
' Append the values from the current source record
rs.Append (RecordAt("/SOURCES/1").Self)
' Append a row with two text strings
rs.Append("This is one field value", "This is another")
Clear Method
The Clear method removes all rows from a row set.
Syntax
rowset.Clear
320
Type
Required
Description
DJRowSet
Yes
Reference to the DJRowSet object that is the
subject of the property or method invocation.
Objects
Example
The following example clears the row set rs if there are any rows in the row set.
If rs.Size > 0 Then rs.Clear
Erase Method
The Erase method is used to erase a row from a row set. The row is specified using the
rownum parameter.
Syntax
rowset.Erase(rownum)
Type
Required
Description
DJRowSet
Yes
Reference to the DJRowSet object that is the
subject of the property or method invocation.
Integer
Yes
Row index of the row to be erased.
Exceptions
The Erase method may return the following exceptions if there is an error at run time:
Exception
Description
ERR_TYPEMISMATCH
Returned if an invalid row index is passed to the method.
Example
The following example erases the last row of the row set rs if there are any rows in the row
set.
If rs.Size > 0 Then rs.Erase(rs.Size)
Insert Method
The Insert method inserts a new row in a row set. The row is inserted in the row set at the
position specified by the rownum parameter. If a row with that index already exists, it is
moved further down in the row set and can be indexed with rownum + 1. Rows can be
inserted with index values of 1 to rowset.Size + 1.
The new row is created using a list of values or by copying values from a DJRecord object.
321
Syntax
rowset.Insert(rownum, record)
OR
rowset.Insert(rownum, values)
Type
Required
Description
DJRowSet
Yes
Reference to the DJRowSet object that is the subject of the
property or method invocation.
Integer
Yes
Row index for where the row is to be inserted.
DJRecord
Yes
Reference to the DJRecord used to insert a new row in the
row set.
Variant
Yes
Comma-delimited list of values used as field values for a
new row in the row set.
Exceptions
The Insert method may return the following exceptions if there is an error at run time:
Exception
Description
ERR_TYPEMISMATCH
Returned if any invalid parameters are passed to the method.
Example
The following example creates a new DJRowSet object and inserts a row at the beginning
of the row set:
Dim rs as DJRowSet
Set rs = New DJRowSet
' Insert a row with two text strings and one integer as the first row:
rs.Insert(1, "First value", "Second Value", 3)
Operators
New Operator
The New operator creates a new instance of a DJRowSet object. The operator returns a
reference to the new object. Typically, this reference is assigned to an object variable that
322
Objects
has been declared with a compatible type. The assignment is done using the Set
statement.
Syntax
New DJRowSet
Example
The following example creates a new row set and adds a row of data to it:
Public rs As DJRowSet
Set rs = New DJRowSet
' Append some a row
rs.Append(1, 2, 3, 4, 5)
DOMDocument Object Type
The DOMDocument type represents an XML document. It contains at least one node, of
type DOM_ELEMENT_NODE, which is the root element of the document.
The following are four ways to create a DOMDocument:
• Use the ParseXML function on a string. The string is expected to be a byte
representation of the XML document (i.e. each Unicode character in the string
contains character values from 0 to 255).
Dim doc as DOMDocument
Dim xml
xml = "<abc><def>text</def></abc>"
set doc = ParseXML (xml)
• Use the ParseXMLFile function on a file. The file may represent a URI.
Dim doc as DOMDocument
Set doc = ParseXMLFile("testfile.xml")
• Use the New operator. This requires one parameter, which is the name of the root
element of the document.
Dim doc as DOMDocument
Set doc = new DOMDocument "DOMTest"
• Use the Self property to pass a reference to the DOMDocument object for a userdefined function. For an example of how to refer to an object inside a user-defined
function, see DocumentElement Property.
323
Dim doc as DOMDocument
userFunction (doc.self)
The DOMDocument supports a few properties and methods, mostly concerned with
getting or creating DOMNode objects.
Property
Type
Access
Description
DocumentElement Property
DOMNode
RO
Get the root element of the document.
Self Property
DOMDocument
RO
Return a reference to the
DOMDocument object.
Method
Type
Description
CreateCDATASection Method
DOMNode
Create a CDATA node.
CreateElement Method
DOMNode
Create a DOM element node.
CreateTextNode Method
DOMNode
Create a text node.
Print Method
String
Print the DOM object to an XML
string.
Operator
Description
New root_element_name
Create a new object.
Properties
DocumentElement Property
The DocumentElement property returns the root element of the DOMDocument.
Syntax
dom.DocumentElement
324
Type
Required
Description
DOMDocumen
t
Yes
Reference to the DOMDocument that is the
subject of the property or method invocation.
Objects
Examples
The following example shows how to get the root element from a DOMDocument called
doc.
Dim rootnode as DOMNode
Set rootnode = doc.DocumentElement
Self Property
The Self property is used for getting a reference to an object that can then be passed as an
argument to a function or method call. The reason for having a special property for getting
the object reference is to resolve an ambiguity with the default property, Value. This is
similar to the distinction between normal variable assignment (Let) the use of Set for
assigning object variables.
When a DOMDocument object variable is used without an associated property or method,
the integration language processor assumes an implied access of the Value property.
Syntax
doc.Self
Type
Required
Description
DOMDocument
Yes
Reference to the DOMDocument object which is
the subject of the property or method
invocation.
Example
This example shows how to refer to an object inside a user-defined function.
Function userFunction(doc as DOMDocument)
Dim rootNode as DOMNode
set rootNode = doc.DocumentElement
Methods
CreateElement Method
This method creates a new document element with a DJNode type of
DOM_ELEMENT_NODE and with the name. A reference to the new DJNode object is
returned as the result of the method.
325
Syntax
dom.CreateElement(name)
Type
Required
Description
DOMDocument
Yes
Reference to the DOMDocument object that is
the subject of the property or method
invocation.
String
Yes
Name for the new element node.
Exceptions
The CreateElement method may return the following exceptions if there is an error at run
time.
Exception
Description
ERR_DOMERROR
Returned if the method is unable to create the new element.
Example
The follow code snippet creates a new element, TestNode, in the DomDocument doc.
Dim newnode as DOMNode
Set newnode = doc.CreateElement("TestNode")
CreateTextNode Method
This method creates a new document element with a DJNode type of DOM_TEXT_NODE.
A reference to the new DJNode object is returned as the result of the method.
Syntax
dom.CreateTextNode(pcdata)
326
Type
Required
Description
DOMDocument
Yes
Reference to the DOMDocument object that
is the subject of the property or method
invocation.
String
Yes
String expression used to provide the initial
data for the object.
Objects
Exceptions
The CreateTextNode method may return the following exceptions if there is an error at run
time.
Exception
Description
ERR_DOMERROR
Returned if the method is unable to create the new
element.
Example
‘Creates a new DOMNode for holding parsed character data.
Dim newnode as DOMNode
Set newnode = doc.CreateTextNode("Some PCDATA")
CreateCDATASection Method
This method creates a new document element with a DJNode type of
DOM_CDATA_SECTION_NODE. A reference to the new DJNode object is returned as the
result of the method.
Syntax
dom.CreateCDATASection(cdata)
Type
Required
Description
DOMDocument
Yes
Reference to the DOMDocument object that is the subject of
the property or method invocation.
String
Yes
String expression used to provide the initial data for the
object.
Exceptions
The CreateCDATASection method may return the following exceptions if there is an error
at run time.
Exception
Description
ERR_DOMERROR
Returned if the method is unable to create the new
element.
327
Example
The follow code snippet creates a new DOMNode for holding character data.
Dim newnode as DOMNode
Set newnode = doc.CreateCDATASection("Some character data")
Print Method
Use the Print method to print a DOMDocument object to a string.
The Print method accepts three optional parameters. The first is the encoding to use (one
of the ENC_xxx constants). If not supplied, the default is UTF-8. The second parameter is a
Boolean indicating whether to print an XMLDecl line; the default value is TRUE. The third
parameter is a Boolean indicating whether to attempt to "pretty-print" the document. If
set to TRUE, an attempt is made to insert indentation and newlines to make the result
easier to read. The default is FALSE.
Syntax
dom.Print([encoding][, xmldecl][, prettyprint])
Type
Required
Description
DOMDocumen
t
Yes
Reference to the DOMDocument object that is the
subject of the property or method invocation.
Integer
No
Character set to use for encoding the printed
document.
Boolean
No
Flag indicating whether or not to include an XMLDecl
line.
Boolean
No
Flag indicating whether or not to use pretty-printing.
Exceptions
The Print method may return the following exceptions if there is an error at run time.
328
Exception
Description
ERR_DOMERROR
Returned if the method is unable to print the document.
Objects
Example
The follow code snippet prints a DOMDocument doc using UTF-8 encoding. The printed
document will include an XMLDecl statement and the document is printed without prettyprinting.
Dim pxml
pxml = doc.Print(ENC_UTF8, TRUE, FALSE)
DOMNode Object Type
Conceptually, DOM stores a document as a tree of nodes. All elements, attributes, chunks
of text, etc. are simply different types of nodes. Externally, Data Integrator engine does not
differentiate between different types of nodes (in other words, we only support the one
DOMNode data type). However, internally each node has a specific type, and capabilities
dependent on the type. We provide some methods and properties to manipulate the
various nodes.
Properties
Type
Required
Description
Attribute Property
String
RW
Get/set node attribute value for an
element node.
AttributeCount
Property
Integer
RO
Get attribute count for an element
node.
AttributeNode
Property
DOMNode
RO
Get the nth attribute for the element
node.
FirstChild Property
DOMNode
RO
Get the first child element of the node.
LastChild Property
DOMNode
RO
Get the last child element of the node.
Name Property
String
RO
Get the node name.
NextSibling Property
DOMNode
RO
Get the next sibling of the node.
Parent Property
DOMNode
RO
Get the parent node for the node.
PrevSibling Property
DOMNode
RO
Get the previous sibling of the node.
Type Property
Integer
RO
Get the node type.
Value Property
String
RW
Get/set the value of a node (default
property).
329
Method
Type
Description
AppendChild Method
- NA -
Append a child node to the node.
Print Method
String
Print the DOM object to an XML string.
Operator
Type
Description
New
DOMNode
Create a new object.
Properties
Attribute Property
Use the Attribute property to get or set an attribute value for an element node.
This read/write property may only be applied to an element type of node. It gets or sets
the value of the named attribute. If an attribute by that name does not exist, null is
returned when reading. When writing, if the named attribute does not exist it is created,
otherwise its value is set as specified.
Syntax
node.Attribute(name)
Type
Required
Description
DOMNode
Yes
Reference to the DOMNode that is the
subject of the property or method
invocation.
String
Yes
Attribute name.
Exceptions
The Attribute property may return the following exceptions if there is an error at run time.
Exception
Description
ERR_TYPEMISMATCH
Returned if used with a node other than an element
node.
Example
The following example shows how to set the value for an attribute named testattr.
330
Objects
node.attribute("testattr") = "test value"
AttributeCount Property
This read-only property returns the number of attributes contained in the element.
Syntax
node.AttributeCount
Type
Required
Description
DOMNode
Yes
Reference to the DOMNode that is the
subject of the property or method
invocation.
Exceptions
The AttributeCount property may return the following exceptions if there is an error at run
time.
Exception
Description
ERR_TYPEMISMATCH
Returned if used with a node other than an element node.
Example
The following example shows how to reference attribute count.
element.AttributeCount
AttributeNode Property
This read-only property returns the attribute node at the given position in the element. It
would be used in conjunction with AttributeCount to determine the number of attributes
contained. If the index is out of range an ERR_ARRAYBOUNDS error is returned. Note that
the index is 0-based.
Syntax
node.AttributeNode(attrno)
Type
Required
Description
331
DOMNode
Yes
Reference to the DOMNode that is the subject of
the property or method invocation.
Integer
Yes
Attribute index.
Exceptions
The AttributeNode property may return the following exceptions if there is an error at run
time.
Exception
Description
ERR_ARRAYBOUNDS
Returned if the index is out of range.
ERR_TYPEMISMATCH
Returned if used with a node other than an element node.
Example
The following example shows how to reference attribute nodes:
Dim attr as DOMNode
For ano = 1 to element.AttributeCount
Set attr = element.AttributeNode(ano – 1)
' do something with the attribute node…
next ano
FirstChild Property
Get the first child of a DOMNode object. This read-only property returns the first child of
this node. Nothing is returned if the node does not have a child.
Syntax
node.FirstChild
Type
Required
Description
DOMNode
Yes
Reference to the DOMNode that is the subject
of the property or method invocation.
Example
The following example shows how to reference the first child.
Dim child As DOMNode
332
Objects
Set child = node.FirstChild
LastChild Property
Get the last child of a DOMNode object. This read-only property returns the last child of
this node. Nothing is returned if the node does not have a child.
Syntax
node.LastChild
Type
Required
Description
DOMNode
Yes
Reference to the DOMNode that is the subject of the
property or method invocation.
Example
The following example shows how to reference the last child.
Dim child As DOMNode
Set child = node.LastChild
Name Property
Get the name of a DOMNode object. This read-only property returns the name of the
node. For element and attribute nodes, it returns the actual name of the element or
attribute. For other node types, it returns mostly useless information (i.e. "#text" for a text
node).
Syntax
node.Name
Type
Required
Description
DOMNode
Yes
Reference to the DOMNode that is
the subject of the property or
method invocation.
Example
‘Print the name of a DOMNode object called node.
Print("Node name: " & node.Name)
333
NextSibling Property
Get the next sibling for a DOMNode object. This read-only property returns the next
sibling of this node. Nothing is returned if the node does not have a next sibling.
Syntax
node.NextSibling
Type
Required
Description
DOMNode
Yes
Reference to the DOMNode that is the
subject of the property or method
invocation.
Example
The following example shows how to check for a next sibling:
Dim nextNode As DOMNode
Set nextNode = node.NextSibling
If nextNode Is Nothing Then
Print("No next sibling found")
End If
Parent Property
Get the parent node for a DOMNode object. This read-only property returns the parent
node of the given node, or Nothing if the node does not have a parent (has not been
inserted in the tree).
Syntax
node.Parent
Type
Required
Description
DOMNode
Yes
Reference to the DOMNode that is the subject
of the property or method invocation.
Example
The following example shows how to check to see if a node has a parent:
Dim parent As DOMNode
334
Objects
Set parent = node.Parent
If parent Is Nothing Then
Print("No parent found")
End If
PrevSibling Property
Get the previous sibling for a DOMNode object. This read-only property returns the
previous sibling of this node. Nothing is returned if the node does not have a previous
sibling.
Syntax
node.PrevSibling
Type
Required
Description
DOMNode
Yes
Reference to the DOMNode that is the
subject of the property or method
invocation.
Example
The following example shows how to check for a previous sibling:
Dim prev As DOMNode
Set prev = node.PrevSibling
If prev Is Nothing Then
Print("No previous sibling found")
End If
Type Property
Get the DOMNode type. This read-only property returns the type of the specific node. The
particular values, and their representational names are in this table.
Node_Type
Value
Description
DOM_ELEMENT_NODE
1
Element node
DOM_ATTRIBUTE_NODE
2
Attribute node
DOM_TEXT_NODE
3
PCDATA node
335
Node_Type
Value
Description
DOM_CDATA_SECTION_NODE
4
CDATA section node
DOM_ENTITY_REFERENCE_NODE
5
Entity reference node
DOM_ENTITY_NODE
6
Entity node
DOM_PROCESSING_INSTRUCTION_NODE
7
XML processing instruction node
DOM_COMMENT_NODE
8
Comment node
DOM_DOCUMENT_NODE
9
Document node
DOM_DOCUMENT_TYPE_NODE
10
Document type node
DOM_DOCUMENT_FRAGMENT_NODE
11
Document fragment node
DOM_NOTATION_NODE
12
Notation node
DOM_XML_DECL_NODE
13
XML declaration node
Syntax
node.Type
Type
Required
Description
DOMNode
Yes
Reference to the DOMNode that is the subject of
the property or method invocation.
Example
The following example shows how to check the type of a node:
If node.Type = DOM_XML_DECL_NODE Then
Print("Found an XMLDecl node")
End If
Value Property
Get or set the value for a DOMNode object. This read/write property gets or sets the value
of a node. If an attempt is made to set the value of a node type other than attribute, text
or CDATA an ERR_TYPEMISMATCH exception is returned.
336
Objects
Syntax
node.Value
OR
node.Value = value
Type
Required
Description
DOMNode
Yes
Reference to the DOMNode that is the subject of the
property or method invocation.
String
Yes
String expression used to assign the value to the
node.
Exceptions
The Value property may return the following exceptions if there is an error at run time:
Exception
Description
ERR_TYPEMISMATCH
Returned if the method is unable to create the new element.
Example
The following example shows how to assign a string value to a node:
node.Value = "This is a value"
Methods
AppendChild Method
Append a child DOMNode object to another DOMNode object. This method appends the
given node as the last child of this node. This is how the DOM tree is actually built.
Syntax
node.AppendChild(child)
Type
Required
Description
DOMNode
Yes
Reference to the DOMNode object that is
the subject of the property or method
invocation.
DOMNode
Yes
Reference to the child DOMNode to append.
337
Exceptions
The AppendChild method may return the following exceptions if there is an error at run
time.
Exception
Description
ERR_TYPEMISMATCH
Returned if the argument is not a DOMNode.
Example
The follow example shows how to append a new text node to the root node of a
document.
Dim node as DOMNode
Dim child as DOMNode
Set node = doc.DocumentElement
Set child = doc.CreateTextNode("Some text")
Node.AppendChild(child)
Linking Nodes
In this example, two nodes are created, an Element node, and a Text node. To link the two
nodes, the Text node is declared a child of the element node using the AppendChild
method.
Example
<root>
<firstchild>
</firstchild>
</root>
To create the first node, use the CreateElement method of the DOMDocument object. This
creates tags of the XML document. To create the text node, use the CreateTextNode
method of the DOMDocument object. The final step ties the two nodes together. Use the
AppendChild method to the make the Text node a child of the Element node. See the
example below.
Example
Dim DOM as DOM Doc (sets the document object model)
Dim 1 as DOM Node (sets 1 as a document node)
338
Objects
Dim 2 as DOM Node (sets 2 as a document node)
Dim root as DOM node (sets "root" as a document node)
Set root = DOM.doc element (defines "root" as an element type)
Set 1 = root.firstchild (defines "root" as the parent of
"firstchild")
Set 2 = 1.firstchild (defines node 2 as a child of root)
root.AppendChild (1) (appends firstchild as a child element of root;
creates tags)
Print Method
Use the Print method to print a DOMNode object to a string.
Syntax
node.Print([encoding][, xmldecl][, prettyprint])
Type
Required
Description
DOMNode
Yes
Reference to the DOMNode object that is the subject of
the property or method invocation.
Integer
No
Character set to use for encoding the printed document
(one of the ENC_xxx constants). If not supplied, the
default is UTF-8.
Boolean
No
Flag indicates whether or not to include an xmldecl line.
The default is false. Do not include an xmldecl line.
Boolean
No
Flag indicating whether or not to use pretty-printing. If
set to true, an attempt is made to insert indentation and
newlines to make the result easier to read. The default is
false.
Exceptions
The Print method may return the following exceptions if there is an error at run time:
Exception
Description
ERR_DOMERROR
Returned if the method is unable to print the document.
Example
The follow code snippet prints the root DOMNode for the DOMDocument doc using the
default Print parameters.
339
Dim rootnode as DOMNode
Set rootnode = doc.DocumentElement
Dim pxml
pxml = rootnode.Print()
DJComponent Object Type
The DJComponent object provides enhanced support for queue sessions, iterators,
aggregators, transformers, invokers, and validators.
This object is available through the expression language and API. Used in conjunction with
the DJMessage Object Type, the DJComponent object can be referenced in any expression
within the Map window and any expression step within the Process window.
This object provides transactional handling support of messages and conditional message
puts and gets. The DJComponent ConnectString option is specific to the messaging
middleware supported.
Messaging Support
The DJComponent object can call any MCF component. The message body is set and
retrieved using the DJMessage object.
Properties
The DJComponent object type provides a generic interface for MCF components that
support message queue-like operations.
Property
Type
Access
Description
ConnectString Property
String
WO
Set the connection string for the message
adaptor.
Properties Property
String
RW
Get/set a message adaptor property by name or
by ordinal position.
PropertiesCount Property
Integer
RO
Get the number of message adaptor properties.
PropertyNames Property
String
RO
Get the name of the nth property in the property
list.
340
Operator
Type
Description
New Operator
DJComponent
Create a new object.
Objects
ConnectString Property
Set the connection string for a DJComponent object.
The connection string is a set of semicolon separated attribute-value pairs that specify all
the information the DJComponent object needs to establish a connection with the data
source. The following attributes are supported for the DJComponent connection strings.
Attribute
Description
PASSWORD
Password used for authentication with the security system for the data source.
QUEUE
Name of the queue. This attribute is used for messaging systems.
QUEUEMGR
Name of a queue manager. This attribute is primarily used with server based
messaging systems.
USERID
User name used for authentication with the security system for the data source
Syntax
msgadaptor.ConnectString=connection_string
Type
Required
Description
DJComponent
Yes
Reference to the DJComponent, which is the
subject of the property or method
invocation.
String
Yes
Expression that evaluates to a character
string with connection information.
Deprecated. Use Connect method.
Exceptions
ConnectString returns exceptions if there is an error. The following exceptions can be
returned.
Exception
Description
ERR_PROPASSGN
Returned when an error is returned from the adaptor.
Example
The following example shows a connection string for connecting to a queue with the
Websphere MQ adaptor:
341
Dim q As DJComponent
Set q = New DJComponent "Websphere MQ"
q.ConnectString = "queue=q_in"
Dim msg As DJMessage
On Error Resume Next
Set msg = q.GetMessage()
Properties Property
Get/set a message property value for an element of the property array. Properties
property is used to get or set values for the properties that are part of the message adaptor
configuration.
Property values can be read using either an integer representing the ordinal position of the
property in the array or a string representing the property name. An exception is returned
if the specified property does not exist.
Syntax
msgadaptor.Properties(n) or
msgadaptor.Properties(n) = value
You can also retrieve a property of the GetMessage action.
dim djtrg as djmessage
dim comp as djcomponent
set djtrg = new DJMessage "trg"
set comp = new DJComponent "HideIterator"
comp.properties("hide") = "true"
comp.properties( "opt1","GetMessage") = "This is a test for
DJComponent"
'retrieves the value of the option 'opt1' of the 'GetMessage' action
set djtrg = comp.GetMessage()
filewrite(macrovalue("MCFTarget") &
"TC24584DJComponentIterator.txt", djtrg.body)
342
Objects
Type
Required
Description
DJComponent
Yes
Reference to the DJComponent, which is the subject of
the property or method invocation.
Variant
Yes
Integer value representing the ordinal position of the
property in the property array, or the name of the
property.
String
Yes
Value to assign to specified property.
Exceptions
The Properties property may return the following exceptions if the array index parameter
is invalid.
Exception
Description
ERR_INDEX
Returned if index parameter is out of the valid range of indexes for the array.
ERR_NOSUCHPROP
Returned if the index is a name and there is no property with the given
name.
Example
‘ The following code sets the timeout for a message adaptor to 200 milliseconds:
q.Properties("timeout") = "200"
PropertiesCount Property
Get a count of the number of message adaptor properties in the property array.
PropertiesCount is used to determine how many properties are supported by the message
adaptor and associated with a DJComponent object.
Syntax
msgadaptor.PropertiesCount
Type
Required
Description
DJComponent
Yes
Reference to the DJComponent, which is the
subject of the property or method invocation.
343
Example
The following code prints the message property names and values for each of the
properties of the message adaptor for the DJComponent object.
For i = 1 To msg1.PropertiesCount
Print(q.PropertyNames(i)) & " = " & q.Properties(i) _
& chr$(13) & chr$(10))
Next i
PropertyNames Property
Get a message adaptor property name for an element of the property array.
PropertyNames property is used to look up the name for a message adaptor property by
its ordinal position in the property array.
Syntax
msgadaptor.PropertyNames(n)
Type
Required
Description
DJComponent
Yes
Reference to the DJComponent, which is
the subject of the property or method
invocation.
Integer
Yes
Integer value representing the ordinal
position of the property in the property
array.
Exceptions
The PropertyNames property may return the following exceptions if the array index
parameter is invalid.
Exception
Description
ERR_INDEX
Returned if index parameter is out of the valid range of indexes for the array.
Example
The following code prints the message property names and values for each of the
properties of the message adaptor for the DJComponent object:
For i = 1 To msg1.PropertiesCount
344
Objects
Print(q.PropertyNames(i)) & " = " & q.Properties(i) _
& chr$(13) & chr$(10))
Next i
Methods
Method
Description
BeginTransaction Method
Mark the start of processing by a component so that it can be
committed or rolled back as a single unit of work.
CommitTransaction Method
Commit work performed since the start of a transaction.
GetMessage Method
Return data from a component in a djmessage object.
PutMessage Method
Send data to a component in a djmessage object.
RollbackTransaction Method
Roll back work performed since the start of a transaction.
Execute Method
Passe data to a component in the source message and returns
processed data in the target message.
Reset Method
Reset a component to an initial state.
Connect Method
Connect a component to required resources.
Disconnect Method
Disconnecs a component from required resources.
BeginTransaction Method
Start a new transaction on the message adaptor connected to a DJComponent object.
BeginTransaction starts a transactional session on a message adaptor. If the message
adaptor does not support transactions, calls to this method do nothing.
Syntax
msgadaptor.BeginTransaction()
Type
Required
Description
DJComponent
Yes
Reference to the DJComponent that is the subject
of the property or method invocation.
345
Example
The following example starts a transaction for the message adaptor instance myQueue,
reads a message, and commits the change.
Dim msg As DJMessage
On Error Resume Next
myQueue.BeginTransaction()
Set msg = myQueue.GetMessage()
myQueue.CommitTransaction()
CommitTransaction Method
Commit work done during a transaction on the message adaptor connected to a
DJComponent object.
CommitTransaction makes work done to a message adaptor during a transactional session
permanent. If the message adaptor does not support transactions, calls to this method do
nothing.
Syntax
msgadaptor.CommitTransaction()
Type
Required
Description
DJComponent
Yes
Reference to the DJComponent, which is the
subject of the property or method
invocation.
Example
The following example starts a transaction for the message adaptor instance myQueue,
reads a message, and commits the change.
Dim msg As DJMessage
On Error Resume Next
myQueue.BeginTransaction()
Set msg = myQueue.GetMessage()
myQueue.CommitTransaction()
346
Objects
GetMessage Method
Receive a message from the message adaptor connected to a DJComponent object. The
GetMessage method returns a reference to a DJMessage object.
Syntax
msgadaptor.GetMessage()
Type
Required
Description
DJComponent
Yes
Reference to the DJComponent, the subject of
the property or method invocation.
Exceptions
If there is an error at run time, the GetMessage method may return one of the following
exceptions.
Exception
Description
ERR_EOF
Returned if there are no more messages to retrieve from the
message adaptor.
ERR_OBJNOTSET
Returned when there is an error receiving messages from the
message adaptor.
Example
The following example starts a transaction for the message adaptor instance myQueue,
reads a message, and commits the change.
Dim msg As DJMessage
On Error Resume Next
myQueue.BeginTransaction()
Set msg = myQueue.GetMessage()
myQueue.CommitTransaction()
PutMessage Method
Send a message to the message adaptor connected to a DJComponent object. The
PutMessage method sends the contents of a DJMessage object to the message adaptor.
347
Syntax
msgadaptor.PutMessage(msg)
Type
Required
Description
DJComponent
Yes
Reference to the DJComponent,
which is the subject of the
property or method invocation.
DJMessage
Yes
Reference to the DJMessage
object containing the message to
send.
Exceptions
The PutMessage method may return one of the following exceptions if there is an error at
run time.
Exception
Description
ERR_PROPFAIL
Returned when there is an error sending the message from the message
adaptor.
Example
The following example starts a transaction for the message adaptor instance myQueue,
writes a message, and commits the change.
Dim msg As DJMessage
Set msg = New DJMessage
msg.Body = "<Test>This is a test</Test>"
On Error Resume Next
myQueue.BeginTransaction()
myQueue.PutMessage(msg)
myQueue.CommitTransaction()
Execute Method
Use the Execute method to execute a component associated with a DJComponent object.
Syntax
myComponent.execute(srcmsg, trgmsg)
348
Objects
Type
Required
Description
DJMessage
No (optional)
Source message for DJComponent.
DJMessage
No (optional)
Target message for DJComponent.
Example
The following example shows how to create a DJComponent object to execute a
Transformer component.
Dim srcmsg As DJMessage
Set srcmsg = New DJMessage
Dim trgmsg As DJMessage
Set trgmsg = New DJMessage
srcmsg.Body = "<Test>This is a test</Test>"
Dim myTransformer As DJComponent
Set myTransformer = New DJComponent "NullTransformer"
myTransformer.execute(srcmsg,trgmsg)
' Do something with the target message...
RollbackTransaction Method
Rollback a pending transaction on the MCF component connected to a DJComponent
object.
RollbackTransaction back out changes made during a transaction with the MCF
component. If the MCF component does not support transactions, calls to this method do
nothing.
Syntax
msgadaptor.RollbackTransaction()
Type
Required
Description
DJComponent
Yes
Reference to the DJComponent, which is the
subject of the property or method invocation.
349
Example
The following example starts a transaction for the MCF component instance myQueue,
reads a message, and undoes the effect of the GetMessage on the component by calling
RollbackTransaction.
Dim msg As DJMessage
On Error Resume Next
myQueue.BeginTransaction()
Set msg = myQueue.GetMessage()
myQueue.RollbackTransaction()
Connect Method
Establishes a connection to the message source/destination. Connect calls the component
referenced by DJComponent.
Syntax
myComponent.connect(connectString)
Type
Required
Description
String
No
Establishes the component
connection.
Disconnect Method
Instructs the component to disconnect from its currently established connection.
Disconnect calls the component referenced by DJComponent.
Syntax
myComponent.disconnect()
350
Type
Required
Description
DJComponent
Yes
Disconnects the component from an
established connection.
Objects
Reset Method
Called explicitly as an action to request that the component reset to initialized state, the
beginning of the component lifecycle. Reset calls the component referenced by
DJComponent.
Syntax
myComponent.reset()
Type
Required
Description
DJComponent
Yes
DJComponent to reset.
Exceptions
The component is expected to set an error condition if it fails to reset.
Operators
New Operator
The New operator creates a new instance of a DJComponent object. It takes one
parameter, the name of the MCF component. Once an object is created, the choice of
component can not be changed without recreating the object.
The operator returns a reference to the new object. Typically, this reference is assigned to
an object variable that has been declared with a compatible type. The assignment is done
using the Set statement.
Syntax
New DJComponent queue_type
Type
Required
Description
String
Yes
Expression that evaluates to a string with the name of the data
adaptor to create for the DJComponent object.
Exceptions
The New operator returns exceptions if there is an error creating the object. The following
exceptions can be returned.
351
Exception
Description
ERR_TYPEMISMATCH
Returned if the adaptor type name does not match a registered or licensed
adaptor type.
ERR_OBJNOTSET
Returned if there is an error creating the adaptor instance.
DJMessage Object Type
Message objects can be used to send and receive data. Message objects are containers for
both data and properties. The data part is the message content or payload, while the
properties is used to describe the message to an application so that it can be read and
processed.
Message objects are process global resources, similar to Private variables. The DJMessage
object type provides one interface for accessing the properties and bodies of message
objects. It is important to understand that the DJMessage variables are really references
to the message objects and are not themselves the message container.
Message objects can be used in conjunction with the DJMessage URI scheme as the
following example shows:
' Declare a DJMessage variable
Dim m As DJMessage
' Create the new DJMessage object
Set m = New DJMessage
' Give the message a name
m.name = "abc"
' Set the message body
m.body = "Hello World"
' Change the message body using the DJMessage URI scheme
FileWrite("djmessage:///abc", "This is a test")
' Print the message body to show that the FileWrite has changed the
content
Print(m.body)
In the example, a new message object is created implicitly when the new DJMessage
object is created. Once the message object has a name, it is accessible through either the
DJMessage interface or through the URI scheme.
352
Objects
Property
Type
Access
Description
Body Property
String
RW
Get/set the message body.
Encoding Property
Integer
RW
Get/set the character set encoding used
for the message body.
Name Property
String
RW
Get/set the message name.
Properties Property
String
RW
Get/set a message property by name or
by index.
PropertiesCount Property
Integer
RO
Get the number of message properties.
PropertyNames Property
String
RO
Get the name of the nth property in the
property list.
Method
Description
AddAttachment
Attaches a message. Method parameter is a message object.
AttachmentCount
Returns the number of attachments on a message.
GetAttachment
Retrieves an attachment from a message. Method parameter is either
an integer indicating the attachment index or a string indicating the
attachment name.
RemoveAttachment
Removes an attachment. Method parameter is a string indicating the
attachment name.
Remarks
A message attachment is simply a message that has been attached to another message.
Exceptions
Invalid arguments to addattachment, getattachment, and removeattachment generates
run-time errors.
Example
The following code adds and removes an attachment.
dim foo as djmessage
set foo = new djmessage "foo"
dim bar as djmessage
353
set bar = new djmessage "bar"
foo.addattachment( bar )
LogMessage( foo.attachmentcount())
' should display 1
dim attached_msg as djmessage
set attached_msg = foo.getattachment( 0 )
'OR
set attached_msg = foo.getattachment( "bar" )
foo.removeattachment( "bar" )
Operator
Type
Description
New Operator
DJMessage
Create a new object.
Properties
Body Property
Get/set the body or payload of a message object.
The body property is used to access the data in the message body. Data stored in the
message body is encoded using the encoding specified with the Encoding property.
Syntax
msg.Body
OR
msg.Body = data
Type
Required
Description
DJMessage
Yes
Reference to the DJMessage, which is the
subject of the property or method
invocation.
String
Yes
Data to be assigned to the message body.
Example
The following code creates a new message and adds a message body.
Dim m As DJMessage
354
Objects
Set m = New DJMessage
m.Body = "<Test>This is a test</Test>"
Encoding Property
Get/set the character set encoding for the message body.
The Encoding is used to specify the character set used to encode the data in the message
body. Character sets are identified with integer constants.
When the encoding is changed from one character set to another, the data in the message
body is decoded using the previous character set and re-encoded using the new character
set.
The default encoding is UTF-8(ENC_UTF8).
Syntax
msg.Encoding
OR
msg.Encoding = encoding
Type
Required
Description
DJMessage
Yes
Reference to the DJMessage, the subject
of the property or method invocation.
Integer
Yes
Code for the character set used to encode
the body.
Exceptions
If the property is set to an encoding that is either invalid or not installed, an exception can
be returned.
Example
The following code creates a new message and sets the encoding to ISO 8859-1.
Dim m As DJMessage
Set m = New DJMessage
m.Encoding = ENC_ISO8859_1
m.Body = "<Test>This is a test</Test>"
355
Name Property
Get/set the name of a message object.
Message objects are process global resources that are referenced by name. The Name
property is used to get the name of the message object referenced by a DJMessage
variable or to change its name.
Syntax
msg.Name
‘OR
msg.Name = name
Type
Required
Description
DJMessage
Yes
Reference to the DJMessage, the subject of the
property or method invocation.
String
Yes
Name assigned to the message.
Exceptions
The Name property may return the following exceptions if there is an error assigning a
new name.
Exception
Description
ERR_PROPASSGN
Returned if the name is already used for another message object.
Example
The following code prints the internally assigned name for a new message object. New
message objects are assigned unique names of the form _MessageN, where N is an integer
value.
Dim m As DJMessage
Set m = New DJMessage
Print(m.Name)
Properties Property
Get/Set message property value for an element of the property array.
356
Objects
The Properties property is used to get or set values for message properties. Values are
stored in the DJMessage object as strings. No distinction is made between user defined
properties and message header properties.
Property values can be read using either an integer representing the index of the property
in the array or a string representing the property name. An exception is returned if the
specified property does not exist.
New properties can be added to the properties list by indexing the properties list with a
new name.
Syntax
msg.Properties(n)
‘OR
msg.Properties(n) = value
Type
Required
Description
DJMessage
Yes
Reference to the DJMessage, the subject of the
property or method invocation.
Variant
Yes
Integer value representing the index of the
property in the property array, or the name of
the property. The index starts at zero.
String
Yes
Value to assign to a specified property.
Exceptions
The Properties property may return the following exceptions if the array index parameter
is invalid.
Exception
Description
ERR_INDEX
Returned if index parameter is out of the valid range of indexes for the
array.
ERR_NOSUCHPROP
Returned if the index is a name and there is no property with the given
name.
Example
The following code assigns the string value of "22" to the message property Parts.
msg.Properties("Parts") = "22"
357
PropertiesCount Property
Get a count of the number of message properties in the property array.
PropertiesCount is used to determine how many message properties are defined in a
DJMessage object. It is useful for establishing the upper bound of the index one would use
for iterating over the collection of message properties.
Syntax
msg.PropertiesCount
Type
Required
Description
DJMessage
Yes
Reference to the DJMessage, the subject of
the property or method invocation.
Example
The following code prints the message names and values for all of the properties in the
DJMessage object message:
For i = 0 to msg.PropertiesCount - 1
FileWrite(msg.PropertyNames(i) & " = " & msg.Properties(i))
Next i
PropertyNames Property
Get a message property name for an element of the property array. PropertyNames
property is used to look up the name for a message property by its index in the property
array.
Syntax
msg.PropertyNames(n)
358
Type
Required
Description
DJMessage
Yes
Reference to the DJMessage, the subject of the property
or the method invocation.
Integer
Yes
Integer value representing the index of the property in
the property array. The index starts at zero.
Objects
Exceptions
The PropertyNames property may return the following exceptions if the array index
parameter is invalid.
Exception
Description
ERR_INDEX
Returned if index parameter is out of the valid range of indexes for the array.
Example
The following code copies the message properties from DJMessage object msg1 to msg2.
The properties in msg2 are indexed by property name to ensure that values from the msg1
properties are assigned to the corresponding properties in msg2.
For i = 0 To msg1.PropertiesCount - 1
msg2.Properties(msg1.PropertyNames(i)) =
msg1.Properties(i)
Next i
Operator
New Operator
Create a new DJMessage object.
The New operator creates a new instance of a DJMessage object. The default character set
for encoding the body is UTF-8. The default name for the message object is formed by
concatenating a unique numeric string to a base name of "_Message".
The operator returns a reference to the new object. Typically, this reference is assigned to
an object variable that has been declared with a compatible type. The assignment is done
using the Set statement.
Syntax
New DJMessage
Type
Required
Description
DJMessage
No (optional)
Name of the DJMessage object may be specified.
Example
In this example, the new DJMessage object is named Message1:
359
Public msg As DJMessage
Set msg = New DJMessage "Message1"
Using a DJMessage Object with a Map
This example creates a process that uses a DJMessage object as a target to read data from
an XML file and transforms the data in a map.
This example covers the following topics:
•
•
•
•
•
•
Creating Map Project Files
Creating a Process with a DJMessage Object
Intializing a DJMessage Object
Adding a Transformation Step to a Process
Linking Steps in a Process
Creating a Configuration and Running a Process
Creating Map Project Files
For this example you need to create a map and its associated data and configuration files.
>> To create map project files
1
In Design Manager, create a new project.
2
Create a source dataset that uses the ASCII connector and a target dataset that uses
the XML-DMS connector.
3
Create a map that uses the artifacts.
4
Run the map to create an auto-generated run-time configuration that is saved in the
project.
5
Validate and save the map.
Creating a Process with a DJMessage Object
For this example you declare the DJMessage objects by creating a global variable. You can
also add a DIM statement to the Script step.
>> To create a process with a DJMessage object
1
In Design manager, create a new process.
1
From the Process window, select the View menu, then select Globals.
2
Add a new variable and select the DJMessage type.
360
Objects
3
Add a description, if desired.
4
Save the DJMessage object.
5
Save the process.
Intializing a DJMessage Object
The following procedure explains how to initialize a DJMessage object variable using a
Script step. You can also set the variable in the Start step of a process using a DIM
statement. See DJMessage Object Type.
>> To initialize a DJMessage object
1
Drag the Script step to the canvas.
2
Add the following to initialize the DJMessage object:
- Set msgobject = new DJMessage msgobject
where msgobject is the name of the DJMessage object you created.
- msgobject.body = FileRead("filename"), -3)
where filename is the name of the DJMessage file.
Note The -3 after the filename sets the encoding for file to UTF-8, the only acceptable when
using a DJMessage. This setting does not affect the encoding for the string or the message
body.
3
Save the process.
Adding a Transformation Step to a Process
In this procedure you add a Transformation step to a process and modify the map to
specify the DJ Message object URI as the target of the transformation.
>> To add a transformation step to a process
1
Drag the Transformation step to the canvas.
2
Select the map from the drop-down list.
3
From the Dataset column, click the Edit button for the target dataset.
4
Click the Open button.
5
Click Start Session.
361
6
Replace the path to the XML file with a reference to the DJMessage object in the URI
format: DJMessage:///msgobject, where msgobject is the name of the
DJMessage object you created.
Note You cannot establish a connection to the data source when referencing a DJMessage
object because the Data Integrator engine is unable to connect directly to the message object.
You can save the dataset with the DJMessage URI reference or specify the DJMessage URL with
a project macro that points to the DJMessage object file. If you use a project macro, you must
change the macro value to the DJMessage URL in the run-time configuration. See DJMessage
Object Type for more information.
7
Save the dataset and return to the Process window.
8
Save the process.
Linking Steps in a Process
>> To link steps in a process
1
Click the Link icon and add a link between the Start and Script steps.
2
Create a link between the Script and Transformation steps.
3
Create a link between the Transformation and Stop steps.
4
Validate and save the process.
Creating a Configuration and Running a Process
>> To create a configuration and run a process
1
Run the process to create an auto-generated run-time configuration that is saved in
the project.
2
Validate and run the process.
Using DJMessage and DJComponent Objects in Expressions
Within the expression language, you are able to call messaging objects, namely the
DJMessage Object Type and DJComponent Object Type objects. Some examples of how
you can write the expressions to call the objects follow.
The DJMessage object can be used as a source or target connection using the DJMessage:/
// URI scheme with any file-based connector. The DJMessage object is not tied to the
DJComponent object. DJMessage is independent and can be used without the use of the
DJComponent object to do "virtual messaging" without a formal messaging middleware.
362
Objects
Note It is often preferable to use the Process window to call these objects, because you can
invoke an object, and use that object over multiple steps in a process. For a process example,
search for “message objects” or “DJmessage variables” in the documentation.
The following example uses the Websphere MQ object in conjunction with the DJMessage
object:
Dim q as DJComponent
Set q = new DJComponent "Websphere MQ"
q.connectstring = "queue = queue1"
Dim msg as DJMessage
Set msg as q.GetMessage()
msg.name = "foo"
LogMessage(FileRead("djmessage:///foo"))
This brings the message into memory, not to the disk, thereby increasing speed. If the
queue is readable, the message is removed from the queue when the transaction is
committed. If the browse mode of the queue is set to true, the message will not be
removed from the queue when the transaction is committed.
Message objects are process specific. They can be used within a single process only.
Therefore, multiple processes can have an object called "foo" and they will not conflict.
Destroy all objects at the end of the process by calling DeleteMessage.
See DJMessage Object Type and DJComponent Object Type for details on objects
properties and methods.
Note You can use macros in conjunction with the DJMessage object.
Syntax
djMessage:///myMsg
Example of Putting a Message on a Queue
Dim q as DJComponent
Set q = new DJComponent "Websphere MQ"
q.ConnectString = "queue=queue1"
363
Dim msg as DJMessage
' The message name is optional here
Set msg = new DJMessage "msg1"
' Alternative method to set the message name
' msg.Name = "msg1"
msg.Body = "Test Message 1"
q.PutMessage( msg )
set q = nothing
Example of Getting a Message from a Queue
Dim q as DJComponent
Set q = new DJComponent "Websphere MQ"
q.ConnectString = "queue=queue1"
Dim msg as DJMessage
Set msg = q.GetMessage()
LogMessage( msg.Body )
Set q = nothing
Example of Putting a Message Using Specific Encoding
Dim q as DJComponent
Set q = new DJComponent "Websphere MQ"
q.ConnectString = "queue=queue1"
Dim msg as DJMessage
Set msg = new DJMessage "msg1"
' msg.Encoding = ENC_UTF8
msg.Encoding = -3
msg.Body = "Test Message 1"
q.PutMessage( msg )
set q = nothing
364
Objects
RFH Header Support: Websphere MQ
The DJMessage object supports both RFH and RFH2 headers for Websphere MQ. These
Rules and Formatting Headers (RFH) contain a fixed binary set of properties followed by a
variable set of property values. The differences between the two versions of the RFH
headers are discussed below.
RFH Header Guidelines and Properties
The RFH header guidelines only allow for a single header to exist in a message. The fixed
binary set of properties is followed by a variable set of name/value pairs.
•
•
•
•
•
•
•
•
strucid
version
struclength
encoding
codedcharsetid
format
flags
namevaluestring
RFH2 Header Guidelines and Properties
The RFH2 header guidelines allow for multiple headers to exist in a single message. In
addition, the fixed binary portion is followed by a pair of repeating fields: a four-byte field
which indicates the length of the data field and the data field. The data field is an XML
representation of the data set up in triplets: name, data type and value. In RFH2 headers,
there can be multiple variable portions that contain data in XML format.
•
•
•
•
•
•
•
•
•
strucid
version
struclength
encodingcodedcharsetid
format
flags
namevalueccsid
namevaluelength
namevaluedata
365
Note The namevaluelength* and namevaluedata* properties are the only properties that may
have more than one occurrence in a header.
Specifying RFH and RFH2 Headers
Because messages can contain multiple RFH2 headers and RFH2 headers can have multiple
occurrences of some of their properties, the following scheme specifies the properties.
• To specify an RFH header, the property name begins with ‘rfh'.
• To specify which RFH header in a message is being referenced, the 'rfh' is followed by
a period ('.') and then the number of the header, for example: 'rfh.1'.
• To specify the property name being referenced, the number is followed by a period ('.')
and the name of the property, for example: 'rfh.1.version'.
• If there is more than one occurrence of a property, the property name is followed by
a period ('.') and the number of the occurrence, for example, 'rfh.1.namevaluedata.1'.
The following property reference is a reference to the third occurrence of the
namevaluelength property for the second RFH2 header:
mhandle.properties("rfh.2.namevaluelength.3")
Websphere MQ Header Support
The following examples deal with retrieving header information from the Websphere MQ
component. Data Integrator supports both the RFH1 and RFH2 header types for
Websphere MQ, as well as the MQMD header. In both of the RFH headers, there is a fixed
portion that is fixed Binary and the difference between the headers is in the variable
length that follows.
Supported Header Types
• RFH1: The variable length beyond the fixed header is a set of value pairs.
• RFH2: The header is an XML representation of the data, set up in triplets. RFH2
headers can have multiple headers, but RFH1 headers can have only one. RFH2
headers can be header, message, header, message, etc., or multiple headers at the
beginning.
Example of Creating an RFH2 Header
Dim q as DJComponent
Set q = new DJComponent "Websphere MQ"
q.ConnectString = "queue=queue1"
Dim msg as DJMessage
366
Objects
Set msg = new DJMessage "msg1"
msg.Body = "Test Message with RFH2 header."
' The version number for an RFH2 header
msg.Properties( "rfh.1.version" ) = 2
' The length of the header data
msg.Properties( "rfh.1.namevaluelength.1" ) = 11
' The header data
msg.Properties( "rfh.1.namevaluedata.1" ) = "Header data"
q.PutMessage( msg )
set q = nothing
Example of Reading an RFH2 Header
Dim q as DJComponent
Set q = new DJComponent "Websphere MQ"
q.ConnectString = "queue=queue1"
Dim msg as DJMessage
Set msg = q.GetMessage()
FileWrite( msg.Properties( "rfh.1.version" ), MB_OK, "RFH version"
)
FileWrite( msg.Properties( "rfh.1.namevaluedata.1" ), MB_OK, "RFH
header data" )
FileWrite(msg.Body, MB_OK, "Message body" )
Set q = nothing
For more Websphere MQ technical information, go to the IBM Web site and click the
Websphere MQ links.
Java and Data Types
Java is a strongly-typed language. Each element of data must be described by one of the
valid Java data types, including boolean, byte, char, double, float, integer, long, null and
short.
Tip The boolean value is passed as "1" (true), or "0" (false). The Java special null type can
have only one value, the null reference.
Java is strictly "pass-by-value." For now, just remember that parameters and argument
expressions are passed by their values in Java. Although objects are addressed through
367
reference variables, the variables themselves are passed by the value of the reference.
Here is an explanation of the terms that demonstrates the distinction between pass-byvalue, and pass-by-reference.
• Pass-by-value means that the parameter or argument is evaluated and the value is
copied into a location on the stack that is used to hold the formal parameter value
during method execution.
• Pass-by-reference means that the formal parameter is a pointer (alias, reference) to
the actual parameter.
See http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#37472
for the Java Specification Language on this section.
For an entertaining explanation of pass-by-value and pass-by-reference, see the JavaRanch
site at this link: http://www.javaranch.com/campfire/StoryCups.jsp or see JavaDude at:
http://www.javadude.com/articles/passbyvalue.htm.
Java Class Objects and Scripts
The scripting languages supports Java class objects from within a transformation. The Java
object can be used to call any method available to the object from within its underlying
Java class. You can pass parameters in the method calls and any value returned from the
method call can be used within the transformation.
Tip Boolean values are passed as "0" or "1" in Java.
Example
This is an example of embedded Java objects within Data Integrator. To use this within
expressions, create and declare the Java object in a BeforeTransformation event. To see
this example in action, copy and paste it into a BeforeTransformation execute action.
'Declare and create the JVM object
'Javavm is DJExpression Language's java virtual machine object.
dim jvm as javavm
'-Djava.class.path=" specifies path to location of class file(s) to be accessed using the Java
object.
jvm = new javavm("-Djava.class.path=.")
'Declare and create the Java object. Javaobject is the Java object.
'HelloWorld()" calls java constructor for HelloWorld class
368
Objects
dim jhello as javaobject
jhello = jvm.new HelloWorld()
'Call sayHello() method in HelloWorld.class
jhello.sayHello()
'Call getHelloString( ) method in HelloWorld class and assign Value returned to variable
result
result = jhello.getHelloString()
FileWrite("This is from getHelloString: " & result)
'call and pass a string to getHelloString( ) method in HelloWorld
'class and assign value returned to variable result
result = jhello.getHelloString("from jni")
FileWrite("This is from getHelloString(from jni): " & result)
'call and pass an integer to getHelloString( ) method in HelloWorld
'class and assign value returned to variable result
result = jhello.getHelloString(10)
FileWrite("This is from getHelloString(10): " & result)
'destroy the java object
jhello = nothing
This is the contents of the HelloWorld.java file used to create the HelloWorld.class file:
public class HelloWorld {
public static void main(String[] args) {
HelloWorld h = new HelloWorld();
System.out.println("HelloString is " + h.getHelloString());
h.sayHello();
HelloWorld h2 = new HelloWorld("This is the second constructor");
h2.sayHello();
}
public HelloWorld () {}
public HelloWorld (String s) { hellostring = s; }
369
public void sayHello() {
System.out.println(hellostring);
}
public String getHelloString() {
return "Hello from a String method";
}
public String getHelloString(String u) {
return "getHelloString says '" + u + "'";
}
private String hellostring = "Hello from the HelloWorld class";
}
Transformation Object
During the transformation process, the transformation engine has access to the run-time
configuration as well as engine statistics that may be applicable to the map. These are
available through the Transformation object and can be used in mapping expressions or in
ECA rule conditions. For example, you might use a mapping expression like the following
to generate a column in a reject target that relates the rejected record to the original
source record:
Transformation.RecordCount("/SOURCE")
The Transformation object supports the following read-only properties.
Property
Type
Description
CurrentSourceName
String
Name of active source port
CurrentTargetName
String
Name of the target, based on the context of the action. When
the action is executed during the evaluation of ECA rules on a
control link, the name is the name of the port referenced by the
target side of the control link. In cases where the action is
executed outside of a control link, the property returns an empty
string.
EventParameterString
String
Parameter string for the last event. Used primarily for handling
user-defined events
IterationCount
Integer
Number of iterations specified for the current OutputRecord
action
370
Objects
Property
Type
Description
IterationNumber
Integer
Current iteration number while processing an OutputRecord
action
IterationNumber >= 1 and IterationNumber <= IterationCount
LastErrorCode([target_por
t_name])
Integer
Error code from the last OutputRecord or ExecuteCommand
action on the current target port, or on an optionally specified
target port. If you do not specify a port, the current target port
is used.
LastAbortReasonCode
Integer
Returns the reason code specified in the Abort action of the
current source record. If you do not set a reason code, the
default is 1.
LastErrorMessage([target_
port_name])
String
Error message from the last OutputRecord or ExecuteCommand
action on the current target port, or on an optionally specified
target port. If you do not specify a port, the current target port
is used.
LastRecordAddress([sourc
e_port_name])
String
Record address for the last source record from the current
source port, or on an optionally specified source port. If you do
not specify a port, the current source port is used.
LastRejectReasonCode
Integer
Returns the reason code specified in the Reject action of the
current source record. If you do not set a reason code, the
default is 1.
LastRecordState([source_p
ort_name])
Integer
State for the last source record from the current source port, or
on an optionally specified source port. State values are:
• 1 (active)
• 2 (discarded)
• 3 (rejected)
If you do not specify a port, the current source port is used.
LastRecordType([source_p
ort_name])
String
Record type for the last source record from the current source
port, or on an optionally specified source port. If you do not
specify a port, the current source port is used
LastScriptingErrorCode
Integer
Numeric code for the last scripting error
LastScriptingErrorMessage
String
Message text for the last scripting error
MapName
String
Name of the transformation map
RecordCount([port_name]
)
Integer
Number of records read from a named input port, or the number
of records written to a named output port
371
Property
Type
Description
TotalErrorCount
Integer
Total number of transformation errors counted
TotalRecordsDiscarded([so
urce_port_name])
Integer
Total number of records discarded from all sources for the
transformation process, or total number of records discarded
from a specific source port. If you do not specify a port, the
current source port is used.
TotalRecordsRead([source
_port_name])
Integer
Total number of records read from all sources for the
transformation process, or total number of records read from a
specific source port. If you do not specify a port, the current
source port is used.
TotalRecordsRejected([sou
rce_port_name])
Integer
Total number of records rejected from all sources for the
transformation process, or total number of records rejected
from a specific source port. If you do not specify a port, the
current source port is used.
TotalRecordsWritten([targ
et_port_name])
Integer
Total number of records written to all targets for the
transformation process, or total number of records written to a
specific target port. If you do not specify a port, the current
target port is used.
TransformationState
Integer
Transformation state values are as follows:
• 1 (initializing/active)
• 2 (running)
• 3 (terminated)
• 4 (aborted)
Project Object
During a process, you can use the Project object to access process session and step
information. Each Project object is indexed by the session or step name.
To access the properties of a step, the call to the Project object must come after the step
is complete. You can access the properties of a process session at any point during the
process.
The following table shows the available properties for the Project object. Each property
has read and write access.
372
Objects
Property
Data
Type
Description
Property
Type
Server
String
Server name for the specified process session.
Session
UserId
String
Logon name for the server used by a process session.
Session
Password
String
Password for the server used by a process session.
Session
When a session password is retrieved using the Password
property, the returned password is encrypted. This allows
the password to be assigned to a different session without
revealing the password.
Database
String
Name of the database used in a process session with a
DBMS.
Session
Status
String
Status message for process step.
Step
ReturnCode
Integer
Last return code from process step.
Step
ErrorCount
Long
Number of errors logged for Transformation step.
Step
OutputRecordCoun
t
Long
Number of records written for Transformation step.
Step
RejectRecordCount
Long
Number of records rejected for Transformation step.
Step
User-defined
Variant
User-defined property.
Session or
step
The following errors may occur when attempting to access the project object.
373
Exception
Description
ERR_INDEX
Index for variable is not a valid session or step name.
This can happen when:
• The session or step name is incorrect
• You are attempting to access a step before the step
has been executed
ERR_PROPFAIL
Invalid property references.
This can happen when:
• The property name is incorrect
• You are attempting to access the incorrect property
type (for example, trying to read the server property
for a step)
Example of Logging Step Information
This example logs the return code and status message for a step called Create Tables:
LogMessage("Return code: " & Project("Create Tables").ReturnCode)
LogMessage("Status: " & Project("Create Tables").Status)
Example of a User-Defined Property
This example stores a value in a user-defined property called myProp:
Project("Create Tables").myProp = 123
Example of Logging SQL Session
This example shows how to log information about the SQL session:
crlf = chr(13) & chr(10)
LogMessage("Server: " & Project("test_1").Server & crlf &
"Database: " & Project("test_1").Database & crlf & "User ID: " &
Project("test_1").UserID & crlf & "Password: " &
Project("test_1").Password)
374
Troubleshooting
Troubleshooting
This section includes information on troubleshooting:
• Troubleshooting Expressions
• Stack Overflow
• Expression Tester Utility
Troubleshooting Expressions
If you are having problems writing expressions, follow these guidelines:
1
Determine your level of ability in writing expressions.
- If you are a novice, review numbers 2 through 4. Then read the introductory
sections, starting with Writing Expressions and Basic Elements of an Expression
Realize that in expressions you are referencing the source field, not the target
field. The target field is implied in the expression, since the target is where the
data is directed.
- If you are an intermediate to advanced user, see suggestions 5 through 10.
2
Use the most efficient function for your task.
- Read about it. Look through the function list and choose a function to read about.
Study how the function is used in the example.
- Search for your situation in the documentation. For instance, if you need to parse
phone numbers, type in "phone number" and see what documentation sections
appear. For example, the Format function is on the list. This function helps you
parse phone numbers into your desired format.
- Start spreading the news. Other users may have suggestions for your particular
situation and can tell you what function works best. Others are a great resource
and provide a wealth of knowledge about solving real world problems. Go to our
website, then check out the support communities.
3
Understand the difference between syntax errors and errors in logic.
Syntax is an important consideration when writing expressions. For example, you run
into trouble if you forget to enclose a string in quotation marks.
Logic is another matter. Your arguments must be logical in order to return the data you
expect to the target.
373
Note Script Editor indicates that your expression is valid if your syntax is correct, but your logic
may not be correct. This is because expressions are actually processed at runtime, and errors
in logic are written to the log. See Function Builder.
Validation is invaluable for checking work when using Script Editor. The best way to
remedy errors is to change only one thing and then validate again. If you still get an
error, try another change, and so on. This makes troubleshooting syntax easier than if
you make many changes before validating.
4
Use comments to document your expressions.
Make it a practice to always use short descriptions to illustrate what you are doing in
each line of code. At the very least, include a comment line or two explaining what you
are doing in the entire expression.
Example
'Declare the DJImport object and set its connection string. You
must change the connection string to point to your database and
server. Location: BeforeTransformation event, Execute action:
Set myvariable = new DJImport "SQL Server 7 (OLEDB)"
myvariable.ConnectString =
"Server=Server1;Database=Tester;UserID=sa"
'This is a snippet from a larger body of code. The variable called
"myvariable" has previously been declared.
5
Assign a variable in the code to speed up your transformations.
Using variables in your code can significantly speed up expression processing.
Compare two methods, one without a declared variable, and one with the declared
variable.
Example of Slower, Less Efficient Method
If Len(Trim(Parse(1, FieldAt("/SOURCE/R1/AccountNo"), " "))) = 7
Then
Trim(FieldAt("/SOURCE/R1/AccountNo")) & Space (4)
Else
String ((11 - Len(Trim(Parse(1, FieldAt("/SOURCE/R1/AccountNo"),
" ")))) , "0") & FieldAt ("/SOURCE/R1/AccountNo")
End if
374
Troubleshooting
Example of More Efficient Method, With a Variable
Dim var
var = Len(Trim(Parse(1, FieldAt("/SOURCE/R1/AccountNo"), " ")))
If var = 7 Then
Trim(FieldAt("/SOURCE/R1/AccountNo")) & Space (4)
Else
String((11 - var))) , "0") & FieldAt("/SOURCE/R1/AccountNo")
End If
6
Use the Option Explicit statement.
Make it a regular practice to use the Option Explicit statement in all code modules.
When Option Explicit appears in a module, you must explicitly declare all variables
using the Dim, Private, Public or ReDim statements. If you attempt to use an
undeclared variable name, an error occurs at compile time.
Many programmers consider using Option Explicit helpful in debugging applications,
as it avoids the chance of mistyping a variable name and inadvertently creating new
variables (for example, mistakenly typing MyDoxString instead of MyDocString).
7
Use functions that signal errors in processing.
You can easily interpret errors that occur by using functions or error handing
statements that halt your transformation. Without these measures, mysterious errors
may occur, such as no data being returned to the target file or table. Learn how to send
messages to yourself so that these errors can be flagged and recorded in the log.
Example
'Declare an error handler to trap the error generated from the
stored procedure.
On Error goto ErrHandler
'Execute the stored procedure and assign the Identity value to
the public variable ABnumber.
'This variable can then be used throughout the transformation
process to populate the foreign key fields of the tables.
'Execute the stored procedure with no error generated.
myvariable.SqlStatement = "testing_getIdentity 0"
ABnumber = myvariable.FieldAt(1)
FileWrite("Identity value with no errors = " & ABnumber)
375
'Execute the stored procedure with error generated. Display the
error number and the message returned from the stored procedure.
'Then abort the transformation.
myvariable.SqlStatement = " testing_getIdentity 1"
ABnumber = myvariable.FieldAt(1)
FileWrite("Identity value with errors = " & ABnumber)
'The above statement should not execute, but is included as a
precautionary measure.
'Perform error handling.
'The mapping log file contains the error message returned from
the stored procedure.
'Alternative: perform error handling at the record level using
OnError events.
'ErrHandler:
FileWrite("DJ_Error_description = " & err.description)
FileWrite("DJ_Error_number = " & err.number)
Abort()
8
Use Resume and Resume Next appropriately.
A Resume statement makes the expression resume at the line that caused the error.
Resume Next goes to the line after the one that caused the error. If your error
handling ends with the Resume statement, it could result in an infinite loop.
9
Use the correct operator for the job.
Should you use an = operator, or the Like operator? A logical or a comparison
operator?
10 Learn about flow control for faster processing.
Compare expression code and learn how flow control statements can speed up your
transformations.
See Also
LogMessage Function
Operators
Validating Data Types in Expressions
Flow Control Statements
Stack Overflow
376
Troubleshooting
Variables
Stack Overflow
A working knowledge of how stacks interact with software and the operating system is
beneficial. Here is an overview in relation to data transformations. Pay special attention to
the section regarding how to handle the returned value from functions.
Stack is a data structure, a temporary space in memory that is used by the program to hold
data to be processed. Memory is allocated as needed to accommodate items placed in
stack, and stack must be emptied of its contents during the course of its current use. Stack
operates on a LIFO principle, "last in, first out".
As an example, think of stack as a filing tray. You place documents in the tray because you
know in advance that you will need all of these documents to complete your current task
and you want to be able to retrieve them quickly when they are needed.
If you attempt to place another document in an already full tray, you encounter "stack
overflow". Stack overflow can also occur if you repeatedly forget to handle something that
is causing the stack to get larger and larger, causing it to eventually overflow.
One common cause of stack overflow is when a function is treated as a subroutine. The
best workaround is to declare a temporary variable to hold the return of this function even
if that return is not used in a subsequent expression.
If you reach for the filing tray to remove a document and you have already used all of
them, there is a shortage of documents to complete your process. If this happens in stack,
an error is generated. This error is called "stack underflow".
Note If a function returns a value, the value must be used. If the returned value is not used in
a subsequent expression or elsewhere in the transformation, then it must be stored. Storing
the value satisfies the use requirement.
So, you may ask, "How do I prevent my expressions from generating stack overflow
errors?" Two examples follow.
Example 1 (Incorrect)
This example causes a stack overflow:
For x = 1 to 1000
LogMessage(x)
Next x
The LogMessage function is called, but its value is not used.
377
Example 2 (Correct)
This is the proper way to write this expression:
For x = 1 to 1000
y = LogMessage (x)
Next x
Although the variable y is not used elsewhere in the transformation, it serves as a place to
hold the return of the LogMessage function. It is not placed in the stack, which prevents
this expression from causing stack overflow.
64-Parameter Limitation in Function Arguments
Function parameters are passed on the stack. If the stack is empty, the number of
parameters that can be passed as arguments has a theoretical maximum of 64. However,
if other processes, especially iterative structures, such as For loops, are also using memory
stack resources, then this maximum is reduced. If stack resources are insufficient, you may
receive a stack overflow error message.
For more information on the use of stacks as data structures, see http://
wombat.doc.ic.ac.uk/foldoc/foldoc.cgi?stack.
Expression Tester Utility
The Expression Tester is a command-line utility that is available on full and stand-alone
engine installations of Data Integrator.
Note The Expression Tester must be run locally from the server where Data Integrator is
installed. It is not included in the Client Tools package.
Expression Tester allows you to test and debug EZscript code directly from the command
line, without having to use the Script Editor in the Design Manager. This can be useful for
quickly testing an expression, especially in embedding scenarios.
If you are developing expressions that do not depend on source or target values (or where
the source and target values can be simulated), it can be faster to edit a file and run
exptest. You can use the Print function within your expression (instead of the Msgbox or
LogMessage functions), which speeds up the process even more. You can also use the
Print function to print out the values of variables when the Expression Tester runs.
>> To use the Expression Tester on a Windows server
1
378
At the command line, enter the appropriate directory.
Troubleshooting
- Full: C:\Pervasive\di-full-64bit-10.x.x\runtime\di9
- Stand-alone engine: C:\Pervasive\di-standalone-engine-64bit-10.x.x\runtime\di9
2
Type exptest filename. The file name is the name of a text file that contains the
expression you are testing. If you supply more than one text file, the Expression Tester
runs the files sequentially.
3
Press Enterto execute the program. If there is a return value left on the stack, the
program prints it out on the screen.
>> To use the Expression Tester on a Linux server
1
At the command line, go to the appropriate directory:
- Full: /opt/Pervasive/di-full-10.x.x/runtime/di9
- Stand-alone engine: /opt/Pervasive/di-standalone-engine-10.x.x/runtime/di9
2
Type ./exptest filename. The file name is the name of a text file that contains the
expression you are testing. If you supply more than one text file, the Expression Tester
runs the files sequentially.
3
Press Enter to execute the program. If there is a return value left on the stack, the
program prints it out on the screen.
Using Flags
To run Expression Tester with flags, add the flags before the file name (e.g., exptest -d
filename.txt).
The following flags can be used to modify how the Expression Tester runs:
Flag
Description
-d
Enable debugging. See Debugger Commands
for more information about using the
debugger.
-s
Syntax check only.
-o
Call CoInitializeEx (Windows only).
-p
Enable engine profiling. The engine profile will
be saved as djprof.out.
379
Flag
Description
-gprogfile
Execute the expression in global mode before
any other files.
All user-defined functions in that program file
will be global and available for use by any
others.
-llogfile
Open the specified log file for all types of
messages.
-wwhitelist
Specify a file containing a white list of thirdparty executables.
Debugger Commands
Use the following commands to interact with the debugger when you have activated the
Expression Tester with the debugging option (-d).
Command
Description
H
Display Help text. When the debugger is active,
type the character 'h' to get a list of debugger
commands.
(Empty line)
Step or next, depending on last command.
S [num]
Single step 1 or NUM lines.
N [num]
Single step 1 or NUM lines overfunction calls.
M [module]
Set module for display and breakpoint
commands. If MODULE is not specified, default to
"current" module.
D [num1[:num2]
Display lines. With no arguments display next 10
lines.
If NUM1 is present, display 10 lines starting with
line NUM1.
If NUM2 is present, display NUM2 lines starting
with line NUM1.
380
R
Run to completion or breakpoint.
E expr
Evaluate expression EXPR.
BP [num]
Set breakpoint at current line or line NUM.
Troubleshooting
Command
Description
BR [num]
Remove breakpoint at current line or line NUM.
BC
Clear all breakpoints.
BL
List breakpoints.
Q
Quit execution.
381
382
">
Download
Advertisement
Key features
EZscript variables are all variant.
EZscript supports both functions and subroutines.
EZscript is supported in both Windows and Unix platforms.
EZscript includes custom functions.
EZscript is a scripting language that can be used to write scripts and expressions.
EZscript includes functions, operators, statements, variables, object variables, and error objects.
Frequently asked questions
EZscript is a scripting language that is similar to Visual Basic, but with some notable differences. It is used to write scripts and expressions for Data Integrator.
EZscript variables are all variant, while Visual Basic variables may be of various data types. EZscript supports both functions and subroutines, while Visual Basic distinguishes between them. EZscript is supported on both Windows and Unix platforms, while Visual Basic is only supported on Windows. EZscript does not include all VB script functions, but it does include custom functions that are not available in VB.
EZscript includes custom functions that are not available in VB, such as the file management functions FileRead and FileRename.