AMPScript.dev

AMPScript Code Snippets, A quick reference collection for Salesforce Marketing Cloud developers

AMPScript is Salesforce Marketing Cloud's proprietary scripting language designed for email personalization, dynamic content creation, and data manipulation in SFMC campaigns. As a server-side scripting language, AMPScript enables Marketing Cloud developers to build sophisticated email marketing automation, personalize customer experiences, and integrate data extensions with email templates.

Whether you're learning AMPScript basics, implementing AMPScript functions for Salesforce Marketing Cloud email sends, or optimizing SFMC AMPScript performance, this comprehensive AMPScript reference guide provides essential code examples and best practices.

From AMPScript personalization strings and conditional logic to LookupRows functions, data extension queries, and API integrations, mastering AMPScript syntax is crucial for any Salesforce Marketing Cloud developer, email developer, or marketing automation specialist working with SFMC email studio, Journey Builder, or CloudPages.

Personalization Example
%%[
VAR @firstName
SET @firstName = [FirstName]
IF EMPTY(@firstName) THEN
  SET @firstName = "Subscriber"
ENDIF
]%%
Hello %%=v(@firstName)=%%!
Date Formatting
%%[
VAR @today, @formatted
SET @today = NOW()
SET @formatted = FormatDate(@today, "MMMM d, yyyy")
]%%
Today's date: %%=v(@formatted)=%%
Lookup Example
%%[
VAR @email, @firstName
SET @email = AttributeValue("EmailAddress")
SET @firstName = Lookup("CustomerData", "FirstName", "EmailAddress", @email)
]%%
Welcome back, %%=v(@firstName)=%%!
Conditional Content
%%[
VAR @tier
SET @tier = AttributeValue("LoyaltyTier")

IF @tier == "Gold" THEN
  SET @message = "Thank you for being a Gold member!"
ELSEIF @tier == "Silver" THEN
  SET @message = "You're a valued Silver member!"
ELSE
  SET @message = "Join our rewards program today!"
ENDIF
]%%
%%=v(@message)=%%
For Loop Example
%%[
FOR @i = 1 TO 5 DO
  OUTPUT(CONCAT("Item ", @i, "<br>"))
NEXT @i
]%%
GUID and Random Numbers
%%[
VAR @id, @random
SET @id = GUID()
SET @random = Random(1,100)
]%%
Unique ID: %%=v(@id)=%%  
Random number: %%=v(@random)=%%
Retrieve DataExtension Rows
%%[
VAR @rows, @row, @rowCount, @i
SET @rows = LookupRows("ProductCatalog", "Category", "Shoes")
SET @rowCount = RowCount(@rows)
IF @rowCount > 0 THEN
  FOR @i = 1 TO @rowCount DO
    SET @row = Row(@rows, @i)
    OUTPUT(CONCAT(Row(@row, "ProductName"), "<br>"))
  NEXT @i
ENDIF
]%%
Dynamic Email Subject Line
%%[
VAR @subject, @city
SET @city = AttributeValue("City")
SET @subject = CONCAT("Special offers for ", ProperCase(@city))
]%%
%%=v(@subject)=%%
URL Parameter Capture
%%[
VAR @utm_source, @utm_campaign
SET @utm_source = QueryParameter("utm_source")
SET @utm_campaign = QueryParameter("utm_campaign")
]%%
Source: %%=v(@utm_source)=%%  
Campaign: %%=v(@utm_campaign)=%%
Send Logging Example
%%[
VAR @email, @status
SET @email = AttributeValue("EmailAddress")
SET @status = "Delivered"
InsertData("SendLog",
  "EmailAddress", @email,
  "SendDate", NOW(),
  "Status", @status
)
]%%
Send logged successfully.
Retrieve Subscriber Status
%%[
VAR @status
SET @status = Lookup("Subscribers", "Status", "EmailAddress", emailaddr)
IF @status == "Active" THEN
  SET @msg = "You are subscribed."
ELSE
  SET @msg = "Please confirm your subscription."
ENDIF
]%%
%%=v(@msg)=%%
JSON Parsing Example
%%[
VAR @json, @obj, @name
SET @json = '{"user":{"name":"Alex","age":32}}'
SET @obj = BuildRowsetFromJSON(@json, "user", 1)
SET @name = Field(Row(@obj, 1), "name")
]%%
User name: %%=v(@name)=%%
Format Currency
%%[
VAR @amount, @formatted
SET @amount = 2499.95
SET @formatted = FormatNumber(@amount, "C")
]%%
Total: %%=v(@formatted)=%%
Uppercase / Lowercase
%%[
VAR @name
SET @name = ProperCase(AttributeValue("FirstName"))
]%%
Upper: %%=Uppercase(@name)=%%  
Lower: %%=Lowercase(@name)=%%
Get Send Classification
%%[
VAR @classification
SET @classification = _messageContext
]%%
Send Classification: %%=v(@classification)=%%
String Replace Example
%%[
VAR @text, @clean
SET @text = "Welcome to %%CompanyName%%!"
SET @clean = Replace(@text, "%%CompanyName%%", "SFMC")
]%%
%%=v(@clean)=%%
Row Lookup & Field Access
%%[
VAR @row, @points
SET @row = LookupOrderedRows("LoyaltyMembers", 1, "JoinDate DESC", "EmailAddress", emailaddr)
IF RowCount(@row) > 0 THEN
  SET @points = Field(Row(@row, 1), "Points")
ENDIF
]%%
Your points: %%=v(@points)=%%
Concat and Line Breaks
%%[
VAR @greeting
SET @greeting = Concat("Hello", "<br>", "Thanks for joining us!")
]%%
%%=v(@greeting)=%%
Update Data Extension Row
%%[
VAR @email, @newStatus
SET @email = AttributeValue("EmailAddress")
SET @newStatus = "Updated"
UpdateData("CustomerData", 1, "EmailAddress", @email, "Status", @newStatus)
]%%
Record updated successfully.
Substring and Length
%%[
VAR @text, @sub, @len
SET @text = "Hello World"
SET @sub = Substring(@text, 1, 5)
SET @len = Length(@text)
]%%
Substring: %%=v(@sub)=%%  
Length: %%=v(@len)=%%
IIF Function (Inline IF)
%%[
VAR @age, @category
SET @age = 25
SET @category = IIF(@age >= 18, "Adult", "Minor")
]%%
Category: %%=v(@category)=%%
Add/Subtract Dates
%%[
VAR @today, @future, @past
SET @today = NOW()
SET @future = DateAdd(@today, 7, "D")
SET @past = DateAdd(@today, -30, "D")
]%%
In 7 days: %%=FormatDate(@future, "MM/dd/yyyy")=%%
Date Difference
%%[
VAR @start, @end, @daysDiff
SET @start = "2025-01-01"
SET @end = NOW()
SET @daysDiff = DateDiff(@start, @end, "D")
]%%
Days elapsed: %%=v(@daysDiff)=%%
Trim Whitespace
%%[
VAR @input, @trimmed
SET @input = "  Extra Spaces  "
SET @trimmed = Trim(@input)
]%%
Original: [%%=v(@input)=%%]  
Trimmed: [%%=v(@trimmed)=%%]
UpsertData Example
%%[
VAR @email, @firstName
SET @email = "user@example.com"
SET @firstName = "John"
UpsertData("Subscribers", 1, "EmailAddress", @email, "FirstName", @firstName, "LastUpdated", NOW())
]%%
Data upserted successfully.
IndexOf and Contains
%%[
VAR @text, @position, @found
SET @text = "Marketing Cloud"
SET @position = IndexOf(@text, "Cloud")
SET @found = IIF(@position > 0, "Found", "Not Found")
]%%
Position: %%=v(@position)=%%  
Status: %%=v(@found)=%%
Base64 Encode/Decode
%%[
VAR @original, @encoded, @decoded
SET @original = "Hello World"
SET @encoded = Base64Encode(@original)
SET @decoded = Base64Decode(@encoded)
]%%
Encoded: %%=v(@encoded)=%%  
Decoded: %%=v(@decoded)=%%
HTTP GET Request
%%[
VAR @url, @response
SET @url = "https://api.example.com/data"
SET @response = HTTPGet(@url)
]%%
Response: %%=v(@response)=%%
Delete Data Extension Row
%%[
VAR @email
SET @email = "user@example.com"
DeleteData("TempTable", "EmailAddress", @email)
]%%
Record deleted successfully.
Redirect to URL
%%[
VAR @targetURL
SET @targetURL = "https://www.example.com/promo"
Redirect(@targetURL)
]%%
HTTP POST Request
%%[
VAR @url, @contentType, @payload, @response
SET @url = "https://api.example.com/submit"
SET @contentType = "application/json"
SET @payload = '{"name":"John","email":"john@example.com"}'
SET @response = HTTPPost(@url, @contentType, @payload)
]%%
Response: %%=v(@response)=%%
AttributeValue vs Field
%%[
VAR @sendable, @nonsendable
SET @sendable = AttributeValue("EmailAddress")
SET @nonsendable = Field("CustomField")
]%%
Email: %%=v(@sendable)=%%  
Custom: %%=v(@nonsendable)=%%
MD5 Hash Generation
%%[
VAR @input, @hash
SET @input = "password123"
SET @hash = MD5(@input)
]%%
MD5 Hash: %%=v(@hash)=%%
String Padding
%%[
VAR @num, @padded
SET @num = "42"
SET @padded = PadLeft(@num, 5, "0")
]%%
Padded Number: %%=v(@padded)=%%
RaiseError Function
%%[
VAR @email
SET @email = AttributeValue("EmailAddress")
IF EMPTY(@email) THEN
  RaiseError("Email address is required", true)
ENDIF
]%%
Email is valid.
ClaimRow for Multi-Send
%%[
VAR @row, @code
SET @row = ClaimRow("PromoCodes", "IsClaimed", "EmailAddress", emailaddr)
IF NOT EMPTY(@row) THEN
  SET @code = Field(@row, "PromoCode")
ENDIF
]%%
Your code: %%=v(@code)=%%
TreatAsContent Function
%%[
VAR @dynamicContent, @processed
SET @dynamicContent = Lookup("ContentBlocks", "HTMLContent", "BlockID", "123")
SET @processed = TreatAsContent(@dynamicContent)
]%%
%%=v(@processed)=%%
V Function vs Output
%%[
VAR @name
SET @name = "Marketing Cloud"
Output(Concat("Using Output: ", @name, "<br>"))
]%%
Using V: %%=v(@name)=%%
IsNull and IsNullOrEmpty
%%[
VAR @value1, @value2, @check1, @check2
SET @value1 = ""
SET @check1 = IsNull(@value1)
SET @check2 = IsNullOrEmpty(@value1)
]%%
IsNull: %%=v(@check1)=%%  
IsNullOrEmpty: %%=v(@check2)=%%
System Date Parts
%%[
VAR @today, @year, @month, @day
SET @today = NOW()
SET @year = DatePart(@today, "Y")
SET @month = DatePart(@today, "M")
SET @day = DatePart(@today, "D")
]%%
Year: %%=v(@year)=%%, Month: %%=v(@month)=%%, Day: %%=v(@day)=%%
LookupOrderedRows with Filter
%%[
VAR @rows, @row, @product
SET @rows = LookupOrderedRows("Orders", 3, "OrderDate DESC", "CustomerID", _subscriberkey, "Status", "Completed")
IF RowCount(@rows) > 0 THEN
  SET @row = Row(@rows, 1)
  SET @product = Field(@row, "ProductName")
ENDIF
]%%
Last order: %%=v(@product)=%%
WAT and WATP Functions
%%[
VAR @anchor, @button
SET @anchor = WAT("Click Here", "https://example.com")
SET @button = WATP("Download", "https://example.com/file.pdf")
]%%
Link: %%=v(@anchor)=%%  
Button: %%=v(@button)=%%