AMPscript

What AMPscript is in Marketing Cloud Engagement: where it runs, the three ways to insert it, variables, functions and personalization strings.

A private bank wants every client to get the same quarterly email, carrying their name, their relationship manager and their loyalty points balance read from a table: what writes that personalization inside Marketing Cloud Engagement content, and when is it evaluated?

What AMPscript is and where it runs

AMPscript is, its developer guide says, an interpreted scripting language for Marketing Cloud Engagement that integrates the data in your customer database with your marketing content. Interpreted, here, means that the server reads and runs the code as written, with no compilation step before: the gloss is this page’s, because the guide uses the term without defining it.

It is not a browser language. It is embedded in HTML (hypertext markup language) emails, text emails, landing pages, SMS (short message service) messages and MobilePush push notifications, and the system processes it where it is included, subscriber by subscriber. The moment depends on the channel: in a send, the functions are processed at send time; on CloudPages, when the page loads.

What AMPscript reads and writes is almost always a data extension, Engagement’s database table. This page does not document that object again, nor the contact model the contact key and the subscriber key come from.

The three ways to insert it

Form Opens and closes with What it takes
Inline %%= and =%% A single function, which may nest others
Block %%[ and ]%% Several variables and several functions
Tag <script> and </script> A block declared with SSJS’s syntax

The rule that saves the first error: the closing delimiter is of the same type as the opening one, so a block opened with a tag is not closed with ]%%. The tag carries its two attributes, runat="server" and language="ampscript". Comments go between /* and */, and are taken in the block and in the tag, never inline.

Variables, conditions and loops

Variable names always begin with the at sign. They are declared with Var, one or several on the same line, and are born null; they are given a value with Set. They can only be declared inside a block: not in an inline string.

Keywords, function names and the names of the built-in variables are case-insensitive; the guide documents in Pascal case for consistency, not as a requirement.

Operator What it compares or joins
== != Is equal to, is not equal to
> < Greater than, less than
>= <= Greater or equal, less or equal
and or Both conditions, or either one
not Reverses the logic of the evaluation

Parentheses control the order in which a complex expression is evaluated.

Piece What the guide requires
Conditional If, the condition, Then and EndIf
Its branches Several ElseIf and a single Else
What it evaluates Constants, variables, attributes and data extension values, and function calls
Loop A counter with its initial value, to or downto, the stop value, do and, to close, next
Stop value A number, a variable or a function
Direction to raises the counter by one; downto lowers it

The functions

Counted in the function index on 29 October 2026, there are 141 of them across 15 categories: API, Contacts, Content, Data Extensions, Date & Time, Encryption, HTTP, Math, Microsoft Dynamics CRM, Salesforce, Sites, SMS, Social, String and Utilities. Both figures are the count of that table on that day, not a figure Salesforce publishes. The index adds a Marketing Cloud Next column, a product not documented here.

Parameters go in a fixed order, and the guide’s own example teaches it well: FormatCurrency(number, cultureCode, decimalPlaces, currencySymbol). The last ones are optional, but to pass the symbol you must first pass the decimals, and a parameter you do not want is skipped with null or an empty string. As an argument, a constant, an attribute or a variable will do.

Two warnings the guide gives by name. A function cannot call itself: recursion returns the exception “104 - RecursiveScriptError”, and the email, SMS or push that causes it counts as “Errored/NotSent” against the subscriber error limit threshold. And there are two data structures, not one: the data extension and the rowset, the collection of rows a query returns.

Function What it does with a rowset
LookupRows() Returns it unordered, up to 2,000 rows, case-insensitive
Row() Takes one row; the first is row 1
Field() Takes one field from that row
RowCount() Counts its rows, the step the guide recommends before a loop
Empty() Returns true when it is empty, as IsNull() does
v() Will not output it whole

Three lookup functions — Lookup(), LookupRows() and LookupOrderedRows() — take the ENT. prefix to say that the table lives at the parent Enterprise level. The guide names no others.

Personalization strings and built-in variables

AMPscript ships four groups of ready-made variables: the recipient’s, the sender’s, the system’s time and date strings, and the message context one. Their time and date values are fixed to the day of the send in email and SMS, and to the day the page was rendered on CloudPages.

String What it returns, per the guide
_emailaddr The subscriber’s email address
_fullname The full name from the Full Name profile attribute
_firstname The word before the first space of that name
_lastname The words after that first space
_city The city from the contact’s City field
_status The send status: -1 unspecified, 1 active, 2 bounced, 3 held, 4 unsubscribed
memberid The account identifier, which the guide abbreviates MID and does not expand
replyname The reply name from the account settings
xtmonth The full name of the month
xtmonthnumeric The month as a number from 1 to 12
xtday The day of the month, as a number
xtdayofweek The day of the week
xtyear The year, in four digits
xtshortdate The full date in short format
xtlongdate The full date in long format

The first six are a selection of the recipient’s twenty-one, chosen for brevity; the sender’s replyemailaddress and the six email-footer address fields are missing, and the seven date strings are complete.

A warning this page makes in its own voice, because no source explains it. The developer guide writes these names bare, inside the code; the Help article “Personalization Strings in Email Studio” writes the same names between double percent signs, %%xtmonth%%. Neither document says when each form applies, so this page gives both exactly as each source prints them and infers no rule. What is literal: “Don’t use a personalization string as a column name in a sendable data extension or profile attributes”.

The fourth built-in variable, _messagecontext, says in which context the content is being rendered, and combined with a conditional it decides what is shown or what code runs.

Value Context, per the guide
SEND An email sent to a subscriber; not when that email is viewed as a web page
VAWP A sent email viewed as a web page
PREVIEW An email in preview or in the Email Studio editor
VALIDATION An email validated with the validation option
FTAF An email forwarded to a friend
LANDINGPAGE Content viewed on a landing page or a microsite
SITE Content viewed on a CloudPages page
LINKRESOLUTION A page viewed after clicking a link in an email
SMS An SMS message sent to a subscriber
SOCIAL Email content shared with Social Forward

Help publishes one more value, VIEWSENT, which the developer guide does not carry; this page names it for what it is, a value only Help prints. The use the guide proposes is twofold: changing what the reader sees, and keeping code from running where it should not. Its example is UpsertDE(), which writes to a table when the customer views the email and which you do not want to run while testing.

The order in which an email is processed

Order in which Engagement processes an email's AMPscript, and how far a variable's value reachesAn email has four components that can carry AMPscript, and Marketing Cloud Engagement processes them in a fixed order that is not the order in which the reader sees them. The order, in a single column from top to bottom, is: first the preheader text, second the HTML body, third the text body and fourth the subject line. Each arrow points forward along that order and means that a variable given a value in one component keeps that value in the ones that come after, never in the ones before. Hence the practical consequence: a variable set in the subject line, which is processed last, is null in both bodies.still availablestill availablestill available1. Preheader text2. HTML body3. Text body4. Subject line

Engagement does not run the code piece by piece: it processes it in a batch, as the final step of the send. Hence the case the guide uses as a warning. If the send writes the subscriber’s data to a table and the email uses InsertDE() to add it, a duplicate key error fires, because the send had already added it; the function that does not clash is UpsertDE().

Inside the email, the interpreter goes from the beginning of the document to the end, but the four components that can carry code have their own order, the diagram’s. The consequence is the one the diagram draws: a variable set in the HTML body has the same value in the text body and in the subject line, and one set in the subject line is null in both bodies.

AMPscript or SSJS

The boundary with Server-Side JavaScript (SSJS), Engagement’s other personalization language, is set by the source the two pages share, and this page goes no further than it. That source gives four factors for choosing: AMPscript handles inline personalization and simple conditionals simply and efficiently, handles better the case where each subscriber sees unique content, and has a shorter learning curve; in SSJS’s favour, that JavaScript is widely known and many people can apply what they already know. And one explicit recommendation: the vast majority of tasks are done with AMPscript, and the SSJS Core library is reserved for landing-page tasks with no appropriate AMPscript function. The rest of SSJS belongs to its own page.

What to choose in each case

What has to be solved What the guide says
Personalizing one line or a simple conditional AMPscript, inline
Declaring variables and calling several functions A block, not an inline string
Unique content per customer AMPscript, which the guide says handles it better
A landing-page task with no appropriate function The SSJS Core library functions
Reading several rows from a table LookupRows(), up to 2,000 rows
Keeping code from running in a preview A condition on _messagecontext
Reading a table at the parent Enterprise level The ENT. prefix on the three lookup functions

When not: none of the cited sources says which editions or licences include AMPscript, nor gives a criterion for preferring it to a template with no code. This page claims neither.

Example: reading several rows and writing a list

The example is the one in the LookupRows() reference article, reproduced without changing a line, with its table and its output. It reads from a data extension called MembershipRewardsProgramme, of five rows, in which the Area column is “Chelsea” in the first — Dennis Smithers, 92,374 points — and in the fifth — Jian Yeh, 15,123.

<p>Members in Chelsea:</p>
<ul>
%%[
  Var @membersChelsea, @rowCount

  Set @membersChelsea = LookupRows("membershiprewardsprogramme","area","chelsea")
  Set @rowCount = RowCount(@membersChelsea)

  If @rowCount > 0 then
    For @counter = 1 to @rowCount do
      Var @row, @memberId, @firstName, @surname, @rewardsPoints
      Set @row = Row(@membersChelsea, @counter)
      Set @memberId = Field(@row, "MemberId")
      Set @firstName = Field(@row, "FirstName")
      Set @surname = Field(@row, "Surname")
      Set @rewardsPoints = Field(@row, "RewardsPoints")
]%%
  <li>%%=v(@firstName)=%% %%=v(@surname)=%% (member ID %%=v(@memberId)=%%) - Point balance: %%=v(@rewardsPoints)=%%</li>
%%[
      Next @counter
  EndIf
]%%
</ul>

Seven pieces of this page are in those lines: multiple Var, the three parameters of LookupRows() in lowercase — the function is case-insensitive — the count with RowCount(), the conditional with >, the loop with a variable stop value, the Row() and Field() pair, and the inline form with v(). And one technique the guide documents separately: the block closes before the <li> and reopens after it, to use the counter inside the HTML.

The output the article documents is two list items, those of the first and fifth rows. It is the output the source publishes, reproduced here: nobody has executed this code, because an org is needed, and the only local preview the guide names is a Visual Studio Code (VS Code) extension that it itself calls a community project, not an official Salesforce product, and unsupported.

For the private bank at the top, what changes is the names: the table, the column filtered on, the value searched for and the fields printed. The mechanism is the same and the output no longer is, because the documented output belongs to the article’s data and to no other.

Before publishing in production

  1. Insertion form closed with its own delimiter, and comments only where they are taken (see “The three ways to insert it”).
  2. Variables declared in a block, never inline (see “Variables, conditions and loops”).
  3. Rowset checked before iterating it, with RowCount(), Empty() or IsNull() (see “The functions”).
  4. Parameters in order, and optional ones skipped with null or an empty string (same section).
  5. UpsertDE() where InsertDE() would clash with the send’s key (see “The order in which an email is processed”).
  6. Variables set in the component processed before the one that uses them (same section).
  7. Code that must not run in testing, isolated with _messagecontext (see “Personalization strings and built-in variables”).
  8. No personalization string used as a column name in a sendable data extension or in profile attributes (same section).

Official sources

Back to the knowledge base