AMPscript a Basic Summary

AMPScript is processed on the server by the Marketing Cloud system,  a document is any Marketing Could HTML/text email, landing page or SMS message.
by : Denny Febiana Nurhidayat


AMPScript is processed on the server by the Marketing Cloud system. What this means is that by the time a document is sent to the client it has already had any AMPScript rendered. For this discussion a document is any Marketing Could HTML/text email, landing page or SMS message.

AMPScript functions allows documents to:
  • use relational data stored in data extensions
  • have logic to control rendering
  • apply formatting to variables
  • How to use AMPScript
For the AMPscript script function block wrap AMPScript function with opening %%[ and closing ]%%`` delimiters, for example %%[script]%%`.

For inline AMPscript (or function calls outside or the AMPscript script function block) wrap the AMPScript function with opening %%= and closing =%%`` delimiters, for example %%=function=%%`.

An example of an inline AMPscript function is returning a value, for example %%[ LOWERCASE(Name) ]%%.

%%[
var @FirstName
set @FirstName = [field name in data extension or list]
]%%

Open and closing statements: AMPscript always opens and closes with %%[ and ]%%, respectively.
  • Declaring your variable(s): Next, use “var” to declare the variables you will be calling upon. You can have as many variables as you’d like, but we’ll just keep one for this example.
  • Setting your variable(s): Next, you’ll “set” your variable by telling the AMPscript what information to bring in for the variable you declared above.
  • If you wanted to pull in the variable you just created above, it would look like the code below. When outputting a variable, we’ll always open and close with %%= and =%%, respectively. Additionally, the “v” indicates the function, and tells the code to output the variable.

%%=v(@FirstName)=%%
If you wanted to use this in a subject line, it could look like this:
%%[var @FirstName set @FirstName = [field name in data extension or list]]%% %%=v(@FirstName)=%%, check out this offer

Now that you understand the basics, here are two ways you can use simple AMPscript to improve and personalize your subject lines.

Propercase function
However, depending on the cleanliness of your data, you may find yourself in situations where some subscribers’ data is uppercase, lowercase, or a combination.

The Propercase AMPscript function can help clean up the presentation of this data. For example, instead of all caps “KELLY” or all lowercase “kelly,” you can easily use the Propercase function to transform the data into “Kelly.”

%%[var @FirstName set @FirstName = [field name in data extension or list]]%%
%%=Propercase(@FirstName)=%%, check out this offer

As you can see from the example above, we replaced the “v” with “Propercase” when calling upon the variable.

Depending on your brand voice and subject line intention, there are also AMPscript formatting functions that can be used to make your text all uppercase or all lowercase.

If Not Empty
Let’s continue with our example of personalizing subject lines using first name, but what if you have subscribers who do not have a first name within your data? In this case, you can utilize the If Not Empty function to provide personalized subject lines for subscribers with first name data and a default subject line without personalization for those who do not.

The Not Empty function provides both personalized subject lines and a default subject line if there is no data.

%%[var @FirstName set @FirstName = [field name in data extension or list]]%%
%%[If Not Empty(@FirstName) Then]%%
%%=Propercase(@FirstName)=%%, check out this offer
%%[Else]%%
            Valued Customer, check out this offer
%%[EndIf]%%

While we discussed the examples above in regard to subject lines, the code could be used to personalize other parts of your email, as well.

Below is an example from an email sent by Hallmark. Hallmark used the method above to personalize the body text for subscribers who had first name data, while showing different body text for subscribers without first name data.

Parse First Name from Full with AMPScript

%%[
var @full_name, @first_name
set @full_name = AttributeValue("full_name")
if indexOf(@full_name, " ") > 0 then
  set @first_name = substring(@full_name,1,subtract(indexOf(@full_name," "),1))
endif
]%%
Hello, %%=v(@first_name)=%%.

Format date/time via AmpScript
—————————-
Today’s Date Substitution String (Short Date Format):

%%xtshortdate%%
8/14/2011
—————————-
Today’s Date Substitution String (Long Date Format):

%%xtlongdate%%
Sunday, August 14, 2009
—————————-
Today’s Date MM/dd/yyyy:

%%=Format(Now(),"MM/dd/yyyy")=%%
08/14/2011
—————————-
Today’s Date plus 7 days (no formatting):

%%=DateAdd(Now(), "7","D")=%%
8/21/2011 10:05:55 PM
—————————-
Today’s Date plus 7 days (with formatting – no time):

%%=Format(DateAdd(Now(), "7","D"), "MM/dd/yyyy")=%%

8/21/2011 10:05:55 PM
—————————-
Today’s Date plus 7 days (with formatting – no time):

%%=Format(DateAdd(Now(), "7","D"), "MM/dd/yyyy")=%%

08/21/2011
—————————-
FYI – Today’s Date plus 7 days (Format first; Date add second; Time stamp removed; Defaults to midnight)

%%=DateAdd(Format(Now(),"MM/dd/yyyy"), "7","D")=%%

Constants
Constants are fixed numeric, string or boolean values.

Attributes and Data Extensions
Attributes and data extensions are values referenced from functions and objects. Values are enclosed in square brackets, for example [Data Extension Attribute Name].

Keywords
  • Keywords are variables declared, initialized, and modified within a script.
  • Keywords are prefixed with the @ symbol, for example @Name.
  • Keywords are declared using the [VAR] and [SET] syntax, for example:

%%[
VAR @Name
SET @Name = "Sam Sample"
]%%
@Name
Conditional logic
Conditional logic is used to control to flow of the script.

Conditional logic consists of:
IF syntax which is used to evaluate a condition, keywords include [IF], [ELSEIF], [ELSE] and [ENDIF].
FOR syntax which is used to process through a loop, keywords include [FOR] and [NEXT].

Output
Output renders code inside a code block, for example %%[Output(Now())]%%.

Comments
Comments are ignored by AMPScript and contain a readable annotations that can help to make code easier to understand, for example %%[ /* Insert Comment Here */ ]%%.

Functions
Data Modification Functions
There are 2 types of data modification functions. These are used for send time support and landing page support. These functions allow insert, update, upsert (update/insert), and delete actions to be performed at the subscriber level. Data modification functionality include:

Send time support data modification function includes only the InsertDE function.
Landing page support data modification function includes the InsertData, UpdateData, UpsertData and DeleteData functions.Constants
Constants are fixed numeric, string or boolean values.

Attributes and Data Extensions
Attributes and data extensions are values referenced from functions and objects. Values are enclosed in square brackets, for example [Data Extension Attribute Name].

For a discussion of all data extention functions refer to Data Extension AMPscript Functions. In sumary functions include:
  • ClaimRow and ClaimRowValue are used to return values and data extension records.
  • DataExtensionRowCount is used to return the number of rows in a data extension.
  • DeleteData and DeleteDE are used in different contexts to delete rows from a data extension.
  • ExecuteFilter and ExecuteFilterOrderedRows are used to executes a predefined data filter and return a resultset from a data extension.
  • InsertData and InsertDE are used in different context to insert rows into a data extension.
  • Lookup, LookupOrderedRows, LookupOrderedRowsCS, LookupRows and LookupRowsCS functions return result sets from data extensions.
  • UpdateData, UpdateDE, UpsertData and UpsertDE are used in different contexts to update/upsert a data extension.

Using Server-Side JavaScript with AMPscript

%%[
var @CodeP
set @CodeP = RequestParameter("j")
]%%
<script runat="server">
  Platform.Load("Core","1");
  var CodeP = Variable.GetValue("@CodeP");
  Write("<br>CodeP: " + CodeP);
</script>

Following is example email content showing AMPscript HTTPGet HTTP function. Data extension used for example contains sendable email. To test copy this code block into email contents and preview.

%%[
/* Example email content showing AMPscript HTTPGet HTTP function. Data extension used for example contains sendable email. */
Var @content
Set @content = HTTPGet("http://www.example.com/")
]%%
<table>
 <tr><th>FUNCTION</th><th>RESULT</th></tr>
 <tr><td><a href="http://help.exacttarget.com/en/documentation/exacttarget/content/ampscript/ampscript_syntax_guide/http_ampscript_functions/#HTTPGet">HTTPGet</a> function applied to <code>http://www.example.com</code></td><td>%%=v(@content)=%%</td></tr>
</tr>
</table>

Microsite and landing page functions
Refer to Microsite and Landing Page AMPscript Functions for complete list of microsite and landing page functions. In summary functions include:
  • AuthenticatedEmployeeID, AuthenticatedEmployeeNotificationAddress, AuthenticatedEmployeeUserName, AuthenticatedEnterpriseID, AuthenticatedMemberID and AuthenticatedMemberName functions are used to return information about the authenticated landing page user.
  • CloudPagesURL function provides a way for users to reference a CloudPages URL in an account from an email message. Use this function within an email to pass information via a URL in an encrypted query string.
  • DeleteData function deletes rows from a data extension.
  • InsertData function inserts rows into a data extension.
  • IsNullDefault function is used to return a default value if test is null.
  • LiveContentMicrositeURL function provides a way to return a microsite URL by referencing a coupon name that is being hosted on a microsite.
  • MicrositeURL function provides a way for Enterprise 2.0 users to reference a landing page URL in the top-level business unit in an Enterprise 2.0 account from an email message in any child business unit within the same Enterprise 2.0 account. Use this function within an email to pass information via a URL in an encrypted query string.
  • QueryParameter function returns the value from a query string based the key.
  • Redirect function redirects the recipient's browser to the specified URL.
  • RequestParameter function returns the value of a parameter passed into the query string of a landing page URL or passed via a form post.
  • Example showing AMPscript InsertData function used in microsite or landing page content
Following is example of microsite or landing page content showing AMPscript InsertData function. Target data extension used for example requires nameofEvent and timeofEvent fields. To test copy this code block into microsite or landing page content and preview.

%%[

/* Example microsite or landing page content showing AMPscript InsertData function. Target data extension used for example requires nameofEvent and timeofEvent fields. */

InsertData("ampscripresult", "nameofEvent", "OPEN", "timeofEvent", NOW())

]%%

Mobile variables/functions
Refer to AMPscript Variables for Use with Mobile Messages for complete list of mobile variables/functions. In summary variables/functions include:
  • MMS_CONTENT_URL(O1) - use this function to return the URL of incoming MMS content used in a mobile message.
  • MSG(O1) - use this function to return the specified MO keyword used in a mobile message conversation.
  • NOUN(O1) - use this function to return the specified noun used in a mobile message.
  • Social functions
Refer to Social AMPscript Functions for complete list of social functions. In summary functions include:
  • GetPublishedSocialContent function returns content to be shared on a social network as specified by the region ID.
  • GetSocialPublishURL function retrieves the URL of a social network from a lookup table and creates a link to that social network for use with content to be shared from an email.
  • GetSocialPublishURLByName function returns the URL to the publish content page, including a site name, country code, a region ID, and optional pairs of parameter information, such as ShareThis publisher ID information.
  • Utilities functions
Refer to Utilities AMPscript Functions for complete list of utility functions. In summary utility functions all include functions that to do calculations, encoding/decoding, logical tests and string formatting/manipulation.

Example showing some AMPscript utilities functions functions used in email content
Following is example email content showing some of the AMPscript utilities functions. Data extension used for example contains sendable email and name fields. To test copy this code block into email contents and preview.


%%[
/* Example email content showing some of the AMPscript utilities functions. Data extension used for example contains sendable email and name fields. To test copy this code block into email contents and preview.*/
/* Note that for a field to be displayed in content it first must be assigned to an AMPScript variable. */
Var @subscriber_name
Set @subscriber_name = name
]%%
<table>
 <tr><th>FUNCTION</th><th>RESULT</th></tr>
 <tr><td><a href="http://help.exacttarget.com/en/documentation/exacttarget/content/ampscript/ampscript_syntax_guide/utilities_ampscript_functions/#Add">Add</a> function applied <code>1 + 2</code></td><td>%%=ADD(1,2)=%%</td></tr>
 <tr><td>No function applied to <code>@subscriber_name</code> field</td><td>%%=v(@subscriber_name)=%%</td></tr>
 <tr><td><a href="http://help.exacttarget.com/en/documentation/exacttarget/content/ampscript/ampscript_syntax_guide/utilities_ampscript_functions/#Lowercase">LowerCase</a> function applied to <code>@subscriber_name</code> field</td><td>%%=LOWERCASE(@subscriber_name)=%%</td></tr>
 <tr><td><a href="http://help.exacttarget.com/en/documentation/exacttarget/content/ampscript/ampscript_syntax_guide/utilities_ampscript_functions/#ProperCase">ProperCase</a> function applied to <code>@subscriber_name</code> field</td><td>%%=PROPERCASE(@subscriber_name)=%%</td></tr>
 <tr><td><a href="http://help.exacttarget.com/en/documentation/exacttarget/content/ampscript/ampscript_syntax_guide/utilities_ampscript_functions/#Uppercase">UpperCase</a> function applied to <code>@subscriber_name</code> field</td><td>%%=UPPERCASE(@subscriber_name)=%%</td></tr>
</table>

API AMPscript functions
API AMPscript functions allow AMPscript to work with objects in the Marketing Cloud API. The Marketing Cloud API objects allow various functionallity of the Marketing Cloud to be controlled programmaticly. Example use cases include sending emails and creating data extensions.

Refer to API AMPscript functions for complete list of API AMPscript functions. These functions do not work in emails at the time of send. In these function map to method and properties used with objects. In summary functions include:
  • AddObjectArrayItem used to add item to array.
  • CreateObject used to service API object.
  • Field use to return field from object
  • InvokeCreate used to invoke the create method on the API object.
  • InvokeDelete used to invoke the delete method on the API object.
  • InvokeExecute used to invoke the execute method on the API object.
  • InvokePerform used to invoke the perform method on the API object.
  • InvokeRetrieve used to invoke the retrieve method on the API object.
  • InvokeUpdate used to invoke the update method on the API object.
  • RaiseError use to handle errors.
  • SetObjectProperty used to set a value in the API object.
  • Example showing API AMPscript function to insert a record into a data extension.
Following is example showing how to insert a record into a data extension using an API AMPscript function. In example values will be inserted into the nameofEvent and timeofEvent fields of TargetDE data extension. Note that AMPScript also provides InsertData and InsertDE for inserting data into a data extension.

%%[
/* Create data extension object */
Set @de = CreateObject("DataExtensionObject")
SetObjectProperty(@de,"CustomerKey","TargetDE")
/* Create first field to insert into record */
Set @deProperty_1 = CreateObject("APIProperty")
SetObjectProperty(@deProperty_1,"Name","nameofEvent")
SetObjectProperty(@deProperty_1,"Value","OPEN")
/* Create second field to insert into record */
Set @deProperty_2 = CreateObject("APIProperty")
SetObjectProperty(@deProperty_2,"Name","timeofEvent")
SetObjectProperty(@deProperty_2,"Value",NOW())
/* Add fields to record */
Set @deProperties = CreateObject("APIProperty")
AddObjectArrayItem(@de,"Properties",@deProperty_1)
AddObjectArrayItem(@de,"Properties",@deProperty_2)
/* Insert record into data extension object */
Set @StatCode = InvokeCreate(@de, @StatMessage, @ErrorCode)
/* In production do error check on @StatCode to test success */
]%%
SOURCE:

  1. @benedwards44 benedwards44 Fix headings markup syntax for all pages
    9d61604 on Nov 14, 2017
    Salesforce-Marketing-Cloud-Developer-Edition-Recipes/getting-started-with-ampscript-developer-notes.md
    https://github.com/sfmcdg/Salesforce-Marketing-Cloud-Developer-Edition-Recipes/blob/master/getting-started-with-ampscript-developer-notes.md
  2. KELLY STRODA
    CATEGORY
    #STRATEGY
    AUGUST 23, 2016
    How to Use AMPscript to Improve Email Personalization
    https://www.degdigital.com/insights/use-ampscript-improve-email-personalization/
  3. Put value variable AMPscript in a JS variable
    https://salesforce.stackexchange.com/questions/113778/put-value-variable-ampscript-in-a-js-variable
  4. Parse First Name from Full with AMPScript
    Posted on 7/30/2017 Categories AMPScript, Salesforce Marketing Cloud
    https://sprignaturemoves.com/parse-first-name-full-with-ampscript/
  5. FORMAT DATE/TIME VIA AMPSCRIPT
    DECEMBER 12, 2013
    TROYTHIB
    http://troythibodeaux.com/wordpress/format-datetime-via-ampscript/
  6. Image: AMPscript
    Agadzhanov Sergey
    https://marketplace.visualstudio.com/items?itemName=sergey-agadzhanov.AMPscript

No comments