Blog-2
Salesforce Marketing Cloud Ampscript Basics
- September 10, 2024
- Posted by: Peoplewoo Skills
- Category: Consultant

Scripted Personalization
Why AMPscript?
Why we have scripting
- Advanced dynamic content scenarios
- Accessing relational data
- Accessing subscriber metadata (attributes) & MC metadata
- Data formatting and validation
- Control logic
WHAT DOES THAT MEAN???
- Lookup Flight Stats Data
- Credit Card Number Encrypted
- Update SF Case Status from Landing Page
- 2-Way SMS Conversations
- Online/Offline Location-based Offers
- Dynamic Barcode Generation
- Social Sentiment Offer Generation
- Understanding Channel Context (SOCIAL, PREVIEW, EMAIL)
Languages :-
AMPscript (amp)
- Mainly used in emails & landing pages
- Supported in MobileConnect, MobilePush, Microsites, CloudPages
- Released in 2008
- Fully supported and updated
- Similar syntax to Visual Basic
Server-Side JavaScript (ssjs)
- Landing pages and Interactions Script Activities only (for production)
- In maintenance mode – no support or new functionality will be added
- Follows ECMAScript 3.0 standards (6.0 is the latest)
- No 1:1 AMPscript functionality
- Slower rendering time in OMM (a lot slower)
- Outbound Mail Management (where the code is compiled)
Guide Template Language (GTL)
- Message templates & templating language
- Same message content area across all channels
- Don’t use…
<h1>{{title}}</h1>
<p>{{description}}</p>
AMP & SSJS
How & when + examples
Triggered Send :-
AMPscript
VAR @ts, @tsDef, @ts_sub, @ts_attr, @tsctr, @ts_subkey, @ts_statusCode, @ts_statusMsg, @errorCode
SET @ts = CreateObject(“TriggeredSend”)
SET @tsDef = CreateObject(“TriggeredSendDefinition”)
SET @ts_subkey = RequestParameter(“Email”)
SetObjectProperty(@tsDef, “CustomerKey”, “RequestDemo”)
SetObjectProperty(@ts, “TriggeredSendDefinition”, @tsDef)
SET @ts_sub = CreateObject(“Subscriber”)
SetObjectProperty(@ts_sub, “EmailAddress”, RequestParameter(“Email”))
IF NOT EMPTY(@ts_subkey) THEN
SetObjectProperty(@ts_sub, “SubscriberKey”, @ts_subkey)
ELSE
SetObjectProperty(@ts_sub, “SubscriberKey”, RequestParameter(“Email”))
ENDIF
AddObjectArrayItem(@ts, “Subscribers”, @ts_sub)
SET @ts_statusCode = InvokeCreate(@ts, @ts_statusMsg, @errorCode)
IF @ts_statusCode != “OK” THEN
RaiseError(@ts_statusMsg, 0, @ts_statusCode, @errorCode)
ENDIF
SSJS
var triggeredSend = TriggeredSend.Init(“triggeredSend”);
var status = triggeredSend.Send(“aruiz@example.com”);
Capabilities
- API CRUD (create, retrieve, update & delete)
- Data Extension/List retrieve, lookup & upsert
- Externally/Internally hosted RSS/XML Content Syndication
- Email attachments
- Encryption/Decryption
- Dynamically set URLs
- Interact with Salesforce
- “API” page with Landing Pages
Tools & Testing
Editors
- TextMate (https://github.com/whgfive/AMP-Bundle)
- Sublime (Package Control)
- Any ole’ text editor (Perl)
Scripting Resources
- http://help.exacttarget.com/en/documentation/exacttarget/content/ampscript/
- Chatter
- Email Code Slingers
Understanding Documentation
Lookup(S1, S2, S3, S4)
-
Lookup(“Flights”, “FlightNumber”, “CustomerId”, _subscriberkey)
Quick Testing – Dropbox
%%=V(TreatAsContent(HTTPGet(“DROPBOXLINK”)))=%%
Troubleshooting Techniques
- Comment out as much as possible
- Set everything to variables and output
- Double-check delimiters, quotes, parentheses, etc…
- Double-check names
Introduction to Scripting
Basic Syntax
AMPscript Block vs. Inline
- %%[
- VAR @firstName, @greeting
- SET @firstName = ”William”
- SET @greeting = Concat(“Hello ”, @firstName)
- Output(@greeting)
- ]%%
- %%=Concat(“Hello ”, @firstName)=%%
- %%=V(@greeting)=%%
%%[ Block ]%%
- Declare and set variables
- Process conditional logic (if else)
- Large amounts of data formatting / processing
%%= Inline =%%
- Output variables or function responses
- Embed easily into HTML
- %%[
- VAR @firstName, @greeting
- SET @firstName = ”William”
- SET @greeting = Concat(“Hello ”, @firstName)
- Output(@greeting)
- ]%%
- %%=Concat(“Hello ”, @firstName)=%%
Output
Hello William
Output
Hello William
Best Practices for Variables
- Always DECLARE the variable and SET the value separately
- Always START variable names with letters A – Z (after the @ of course)
- Variable names cannot contain spaces
- Avoid names that are already common system variables or personalization strings
- @emailaddr
- @date
- You can DECLARE multiple variables at once by comma-delimiting the variable names
- VAR @thing1, @thing2
- You can only SET one variable at a time
Declaring & Setting Variables
- %%[
- VAR @firstName, @email, @returnValue
- SET @firstName = ”William”
- SET @email = emailaddr
- SET @returnValue = Concat(@firstName, “ – ”, @email)
- // Make sure you DECLARE and SET separately
- VAR @badSyntax = ”This won’t work”
- ]%%
AMPscript Comments
- %%[
- /*
- This is a block comment
- */
- // This is an inline comment…
- “We’re just like javascript”
- ]%%
Nesting Functions
- %%[
- VAR @firstName, @greeting
- SET @firstName = ”William”
- SET @greeting = Concat(“Hello ”, @firstName)
- Output(Concat(“Hello ”, @firstName))
- ]%%
- // Also works inline…
- %%=Output(Concat(“Hello ”, @firstName))=%%
Various Attribute Sources
- Profile Attributes
- Sendable Data Extension Fields
- Send-Time Attributes
- System Variables
Accessing Attributes from Script Block
- %%[
- SET @profileAttribute = Gender
- SET @profileAttributeWithSpaces = [First Name]
- SET @profileAttributeFormatted = ProperCase([Last Name])
- SET @unknownAttributeName = AttributeValue(@attributeName)
- SET @sendableDEField = FlightNumber
- SET @sendTime = SKU
- SET @systemVariable = MOBILE_NUMBER
- SET @queryString = QueryParameter(“email”)
- ]%%
Accessing Attributes Inline
- %%Gender%%
- %%First Name%%
- %%=ProperCase([Last Name])=%%
- %%=AttributeValue(@attributeName)=%%
- %%FlightNumber%%
- %%SKU%%
- %%MOBILE_NUMBER%%
- %%=QueryParameter(“email”)=%%
Mobile Usage
- %%[SET @msg = MSG(0)]%%
- //Returns the message
- %%[SET @verb = MSG(0).VERB]%%
- //Returns the verb/keyword of the message
- %%[SET @nouns = MSG(0).NOUNS]%%
- //Returns the part of the current message after the verb
- %%[SET @noun = MSG(0).NOUN(1)]%%
- //Returns the second noun in the current message.
SendLogging
- SET @LoyaltyLevel = “1”
- SET @Membership = IIF(NOT EMPTY(member),”TRUE”,”FALSE”)
- SET @ZipCode = Lookup(…)
Common Uses
Conditions
Common Types of Conditions
- IF THEN ELSE ENDIF
- Checks for validity
IF THEN ELSE
- %%[IF expression1 <comparison operator> expression2 THEN]%%
- %%[ELSEIF expression1 <comparison operator> expression3 THEN]%%
- %%[ELSE]%%
- %%[ENDIF]%%
Conditions
- == Is equal to
- != Is not equal to
- > Greater than
- < Less Than
- >= Greater than or equal to
- <= Less than or equal to
- AND Both conditions must be true
- OR Either condition must be true
NOT Reverses the Boolean expression
Combined
- %%[IF expression1 <comparison operator> expression2
- AND [NOT] (expression3 <comparison operator> expression4
- OR expression3 <comparison operator> expression5)
- THEN
- ENDIF]%%
- %%[IF @age > 13 AND loyalty == TRUE THEN]%%
- %%MailingAddress%%
- %%[ENDIF]%%
- %%[IF NOT empty(MailingAddress) THEN]%%
- %%MailingAddress%%
- %%[ENDIF]%%
Utilities
Common Types of Utilities
- DateTime Functions
- Math Functions
- Formatting Text, Numbers or Currency
- Validation & Parsing
Common DateTime Scenarios
- SET @today = Now()
- // –> 8/28/2013 12:05:00 PM
- SET @formatted = Format(@today, “MM/dd/yyyy”)
- // –> 08/28/2013
- SET @tomorrow = DateAdd(@today, 1, “D”)
- // –> 8/29/2013 12:05:00 PM
- SET @theYear = DatePart(@today, “year”)
- // –> 2013
Common Formatting Scenarios
- SET @uppercaseName = Uppercase(“william”)
- // –> WILLIAM
- SET @capitalizedName = ProperCase(“william garrison”)
- // –> William Garrison
- SET @fullName = Concat(@firstName, “ ”,@lastName)
- // –> William Garrison
- SET @replacedName = Replace(@fullName, “William”, “John”)
- // –> John Garrison
Common Validation Scenarios
- SET @firstName = “William”
- SET @emptyTest = Empty(@firstName)
- // –> false
- SET @result = IIf(Empty(@firstName), “Friend”, @firstName)
- // –> William
- SET @emailTest = IsEmailAddress(“wgarrison@salesforce.com”)
- // –> true
Common Parsing Scenarios
- SET @firstLetter = Char(“william”, 1)
- // –> a
- SET @regexResult = ProperCase(“ABC_123_DEF_456”, “.*_([0-9]+)_.*_([0-9]+)”, 1)
- // –> 123
Query Parameters
- SET @fn = QueryParameter(“fn”)
- // –> rachel
- SET @ln = QueryParameter(“ln”)
- // –> morris
Content
Common Types of Content Functions
- Content areas
- Treating data as content
Content Areas (Email Only)
- SET @ca1 = ContentArea(“123456”)
- // –> Retrieves the content from id 123456
- SET @ca2 = ContentAreaByName(“My Contents\Ad Block 250px”)
- // –> Retrieves the content from a named content area
Treating as Content
- SET @fn = QueryParameter(“fn”)
- // –> rachel
- SET @ln = QueryParameter(“ln”)
- // –> morris
HTTP + Content
Common Types of HTTP Functions
- Retrieval (HTTPGet/HTTPPost)
- Link wrapping
- Query Parameters
Retrieve XML
- SET @blogXML = AttributeValue(“BlogXML”)
- SET @blogXML = HTTPGET(“http://news.yahoo.com/rss/entertainment”)
- // –> Raw XML String
Convert XML into Rowset
- SET @titles = BuildRowSetFromXML(@blogXML, “//item/title”, 1)
- SET @descriptions = BuildRowSetFromXML(@blogXML, “//item/description”, 1)
Loop Over Each Row in the Rowset
- SET @count = RowCount(@titles)
- FOR @i = 1 TO @count DO
- SET @currentTitle = Row(@titles, @i)
- SET @currentDescription = Row(@descriptions, @i)
- // –> Title Row at @i Index & Description Row at @i Index
- // Additional processing code goes here…
- NEXT @i
Access a Field from the Row
- SET @title = Field(@currentTitle, “Value”)
- // –> McCartney Added to iHeartRadio festival lineup
- SET @description = Field(@currentDescription, “Value”)
- // –> <p><a href=“http://news.yahoo.com/mccartney-added..
Retrieving Data
Retrieving a Column Value from a DE Row
- SET @flightNo = Lookup(“Flights”, “FlightNumber”, “CustomerId”, _subscriberkey)
- // –> 385
Retrieving a Set of Rows from a DE
- Set Values for the Where Clause
- Execute a Lookup to Retrieve a Rowset
- Loop Over Each Row in the Returned Rowset
- Access a Field from the Row
Updating Data
Upserting a DE Row from an Email
- Set Values for the Where Clause
- Set Values to be Upserted
- Execute the Upsert
- No Value is Returned
Set Values for the Where Clause
- SET @subKey = _subscriberkey
- SET @airline = “American Airlines”
Execute a Lookup to Retrieve a Rowset
- SET @flights = LookupRows(“Flights”, “CustomerId”, @subKey, “Airline”, @airline)
- // –> Rowset of every row that matched criteria
Execute a Lookup to Retrieve a Rowset
- SET @flights = LookupOrderedRows(“Flights”, 0, “Departure ASC”, “CustomerId”,
@subKey, “Airline”, @airline) - // –> Rowset of every row that matched criteria, sorted by Departure
- SET @flights = LookupOrderedRows(“Flights”, 3, “Departure ASC”, “CustomerId”,
@subKey, “Airline”, @airline) - // –> Rowset of the first 3 rows that matched criteria, sorted by Departure
Loop Over Each Row in the Rowset
- SET @count = RowCount(@flights)
- FOR @i = 1 TO @count DO
- SET @currentRow = Row(@flights, @i)
- // –> Row at @i Index
- // Additional processing code goes here…
- NEXT @i
Access a Field from the Row
- SET @flightNo = Field(@currentRow, “FlightNumber”)
- // –> 385
- SET @departure = Field(@currentRow, “Departure”)
- // –> 8/29/2013 09:15:00 AM
Retrieving a Set of Rows from a DE
- Set Values for the Where Clause
- Execute a Lookup to Retrieve a Rowset
- Loop Over Each Row in the Returned Rowset
- Access a Field from the Row
Updating Data
Upserting a DE Row from an Email
- Set Values for the Where Clause
- Set Values to be Upserted
- Execute the Upsert
- No Value is Returned
Set the Values for the Where Clause
- SET @subKey = _subscriberkey
- SET @flightNo = 385
Set the Values to Be Upserted
- SET @delayed = true
- SET @notifiedDate = NOW()
Execute the Upsert
- UpsertDE(“Delays”, 2, “CustomerId”, @subKey, “FlightNumber”, @flightNo,
“IsDelayed”, @delayed, “NotifiedDate”, @notifiedDate) - // –> No return value
Execute the Upsert
- UpsertData(“Delays”, 2, “CustomerId”, @subKey, “FlightNumber”, @flightNo,
“IsDelayed”, @delayed, “NotifiedDate”, @notifiedDate) - // –> Number of rows affected
Upserting a DE Row from an Email
- Set Values for the Where Clause
- Set Values to be Upserted
- Execute the Upsert
Best Practices
- Data Management
- Minimize lookup calls by combining data needed beforehand into sending DE or limited # of DEs using queries, filters, etc
- LookupRows vs. Lookups
- Limit count on lookups
- Always use conditionals to validate variable values needed for logic
- TreatAsContent for caching
- Don’t RaiseError() as a segment – filter the data
- For troubleshooting print variable values into content
- SSJS does not belong in production code