AMPscript es el lenguaje de scripting propietario de Salesforce Marketing Cloud Engagement diseñado principalmente para personalizar contenido y trabajar con datos durante el renderizado de mensajes y páginas. Gracias a AMPscript podemos generar experiencias personalizadas 1:1 para cada contacto durante el renderizado del mensaje o la página.
Analogía: AMPscript funciona como la cocina de un restaurante. El comensal no recibe la receta ni observa la preparación de los ingredientes; únicamente recibe en su mesa el plato final terminado.
01 · ¿QUÉ ES AMPSCRIPT Y PARA QUÉ SIRVE?
AMPscript fue concebido para resolver las necesidades directas de comunicación personalizada en Marketing Cloud. Su propósito fundamental es permitir a los desarrolladores y especialistas técnicos:
- Incrustar atributos dinámicos de suscriptores (nombre, saldo de puntos, ciudad, fecha de renovación).
- Ejecutar lógica condicional (ej: mostrar un banner específico según la categoría de cliente o idioma de preferencia).
- Consultar y cruzar datos almacenados en Data Extensions mediante funciones de búsqueda.
- Formatear valores y fechas según patrones estándar de presentación.
- Gestionar enlaces con tracking dinámico mediante
RedirectTo(), ayudando a conservar el seguimiento de clics cuando el destino del enlace proviene de una variable o cálculo.
Cuando necesitas cruzar datos entre tablas, AMPscript ofrece funciones de búsqueda como:
Lookup(): Busca registros utilizando una condición y devuelve el valor de una columna específica correspondiente a una coincidencia. Cuando sea posible, utiliza criterios que identifiquen con claridad el registro que necesitas.LookupRows(): Busca las filas que cumplen una condición y devuelve un conjunto de resultados de hasta 2.000 filas.
| Tecnología | Enfoque Principal | Tipo de Proceso | Casos de Uso Ideales |
|---|---|---|---|
| AMPscript | Personalización 1:1 en mensajes y páginas | Render / Send-Time | Contenido dinámico en emails, SMS, Push, lookups directos y reglas condicionales. |
| SSJS (Server-Side JavaScript) | Lógica programática compleja e integraciones | Ejecución Programática | Procesamiento de JSON, llamadas a APIs REST/SOAP externas, Script Activities en Automation Studio y CloudPages complejas. |
| SQL (Query Activity) | Transformación y segmentación masiva de datos | Proceso por Lotes (Batch) | Unión de Data Extensions (JOINs), segmentación de audiencias y preparación de bases de datos antes del envío. |
02 · ¿DÓNDE SE PUEDE USAR AMPSCRIPT?
AMPscript puede utilizarse en múltiples canales y contextos de Marketing Cloud Engagement:
En líneas de asunto (Subject lines), Preheaders, bloques HTML, atributos de enlaces dinámicos con RedirectTo() y bloques condicionales.
En MobileConnect para enviar SMS personalizados y en MobilePush para personalizar notificaciones push.
En Landing Pages, centros de preferencias de suscripción y formularios que capturan parámetros de URL al momento de la solicitud web.
Bloques de contenido o código reutilizable centralizados en Content Builder que pueden invocarse mediante ContentBlockByKey() o ContentBlockById().
03 · ¿CÓMO PROCESA SALESFORCE UN EMAIL CON AMPSCRIPT?
Para comprender AMPscript sin entrar todavía en la arquitectura interna de Salesforce, podemos representar el proceso mediante el siguiente flujo conceptual simplificado:
IF/ELSE) y las funciones de formateo o validación.%%=v(@nombre)=%% se sustituyen por el texto o HTML resultante.SET, Set y set son aceptados por el lenguaje). Aun así, se recomienda mantener una convención consistente para facilitar la lectura y mantenimiento del código.
04 · SINTAXIS BÁSICA Y DELIMITADORES
Las dos formas de AMPscript que utilizarás con mayor frecuencia son:
1. Bloques de Código: %%[ ... ]%%
Los bloques %%[ ... ]%% se utilizan principalmente para ejecutar lógica, declarar variables, preparar datos, realizar cálculos y evaluar condiciones.
Instrucciones como VAR, SET e IF no generan contenido visible por sí mismas. Normalmente se utiliza AMPscript inline (%%= =%%) para mostrar resultados, aunque AMPscript también dispone de funciones como Output(), que permiten insertar en el contenido el resultado de otra función desde un bloque de código.
%%[ /* 1. Declaración de variables */ VAR @nombre, @membresia, @descuento /* 2. Asignación de valores */ SET @nombre = AttributeValue("FirstName") SET @membresia = AttributeValue("Tier") /* 3. Lógica condicional (comparación con ==) */ IF @membresia == "VIP" THEN SET @descuento = 20 ELSE SET @descuento = 5 ENDIF ]%%
2. Salida Inline: %%= ... =%%
Se utiliza directamente dentro del cuerpo HTML o texto plano para imprimir el valor de una variable o el resultado de una función en esa posición exacta:
<!-- Salida inline en el cuerpo HTML --> <h1>¡Hola, %%=v(@nombre)=%%!</h1> <p>Tu categoría actual es <strong>%%=v(@membresia)=%%</strong>.</p> <p>Tienes un <span style="color:#00ffff;">%%=v(@descuento)=%%% de descuento</span> en tu próxima compra.</p>
<script runat="server" language="ampscript">...</script>, aunque en la práctica diaria de Email Studio y Content Builder los bloques %%[ ]%% e inline %%= =%% son el estándar habitual.
%%[ ... ]%% para procesar la lógica en el servidor y %%= ... =%% para mostrar los datos en el mensaje.
05 · VARIABLES, ASIGNACIÓN (=) Y COMPARACIÓN (==)
Comprender cómo se crean, asignan y comparan variables es el pilar fundamental de AMPscript.
1. Declaración con VAR y Asignación con SET
En AMPscript, toda variable comienza con el carácter @:
VARdeclara la variable (informa al sistema que la variable existirá).SETasigna un valor a la variable utilizando el operador=.
@firstName).SET toma un valor (ej:
"Ana") y lo guarda dentro de esa caja con el signo =.
Declarar variables explícitamente con VAR hace que el código sea más claro, ayuda a identificar qué variables utiliza el script y mejora sustancialmente su mantenimiento.
2. La Diferencia Crítica: Asignación (=) vs Comparación (==)
Este es uno de los conceptos más importantes para cualquier principiante:
Se utiliza con SET para guardar un valor dentro de una variable.
SET @tier = "VIP"
Significa: "Guarda VIP dentro de @tier."
Se utiliza dentro de IF para comprobar si dos valores son iguales.
IF @tier == "VIP" THEN
Significa: "Comprueba si @tier contiene VIP."
= es como guardar un objeto dentro de una caja.== es como comprobar si lo que hay dentro de una caja coincide con un valor.
3. Tabla de Operadores en AMPscript
A continuación se muestran los operadores tal como se escriben en el código:
| Operador | Significado | Ejemplo en Código |
|---|---|---|
| == | Igual a | IF @tier == "VIP" THEN |
| != | Diferente de | IF @pais != "ES" THEN |
| > | Mayor que | IF @puntos > 100 THEN |
| < | Menor que | IF @saldo < 0 THEN |
| >= | Mayor o igual que | IF @edad >= 18 THEN |
| <= | Menor o igual que | IF @intentos <= 3 THEN |
| AND | Y lógico (ambas deben ser verdaderas) | IF @puntos > 50 AND @activo == "True" THEN |
| OR | O lógico (al menos una verdadera) | IF @tier == "VIP" OR @puntos > 500 THEN |
| NOT | Negación lógica (invierte el valor) | IF NOT Empty(@nombre) THEN |
@s_ para cadenas de texto (strings), @n_ para números y @b_ para booleanos. Ten presente que esta es una propuesta formativa para ayudarte a estructurar tus desarrollos, no un estándar oficial impuesto por Salesforce.
= asigna un valor a una variable; == compara dos valores dentro de una condición de igualdad.
06 · ESTRUCTURAS DE CONTROL: CONDICIONALES IF / ELSE
Las sentencias condicionales permiten evaluar reglas de negocio y adaptar el contenido a las características de cada suscriptor:
IF funciona como el portero de un evento: revisa si el invitado cumple una regla de acceso (condición) y decide qué camino o contenido debe entregársele.
%%[ VAR @segmento, @mensaje SET @segmento = AttributeValue("SegmentoCliente") IF @segmento == "Platino" THEN SET @mensaje = "Acceso a sala VIP exclusiva y envíos gratuitos ilimitados." ELSEIF @segmento == "Oro" THEN SET @mensaje = "Disfruta de un 15% de descuento en tus próximas compras." ELSE SET @mensaje = "Acumula puntos en cada compra y sube de categoría." ENDIF ]%% <!-- En el cuerpo del correo --> <div class="promo-box"> <p>%%=v(@mensaje)=%%</p> </div>
07 · FUNCIONES ESENCIALES PARA TU DÍA A DÍA
A continuación se detallan las funciones fundamentales que todo desarrollador de Marketing Cloud debe dominar para personalización defensiva:
Qué hace: Recupera el valor de un atributo disponible en el contexto del suscriptor. Si no encuentra datos para ese atributo, devuelve null.
IF Empty(@nombre) THEN SET @nombre = "Cliente" ENDIF
Cuándo la usarías: Para recuperar atributos del contacto y combinarlos defensivamente con Empty(), manejando de forma segura datos que podrían no estar disponibles.
En pocas palabras: Recupera atributos del contexto retornando null cuando no hay datos disponibles.
Qué hace: Devuelve True cuando el valor evaluado está vacío (cadena vacía "") o es null.
Cuándo la usarías: Inmediatamente después de AttributeValue() para comprobar si un atributo carece de datos y aplicar un valor por defecto (fallback).
En pocas palabras: Comprueba si un valor está vacío o es null.
Qué hace: Devuelve el valor almacenado en una variable para mostrarlo dentro del contenido.
Cuándo la usarías: En cualquier lugar del HTML o texto plano donde quieras mostrar el valor de una variable.
En pocas palabras: Devuelve el valor almacenado en una variable para imprimirlo.
Qué hace: Une múltiples cadenas de texto, variables o números en un solo string resultante.
Cuándo la usarías: Para construir URLs compuestas, nombres completos o mensajes personalizados combinados.
En pocas palabras: Concatena múltiples textos y variables en uno solo.
Qué hace: Transforma un texto a formato proper case, capitalizando la primera letra de cada palabra.
Cuándo la usarías: Para normalizar de manera sencilla la capitalización de nombres o textos ingresados en mayúsculas o minúsculas desordenadas.
En pocas palabras: Capitaliza la primera letra de cada palabra en un texto.
Qué hace: Da formato de presentación a una fecha según patrones estándar (ej: "yyyy-MM-dd" o "dd/MM/yyyy").
Cuándo la usarías: Para presentar fechas de vencimiento, compra o vigencia en un formato legible. (Nota: FormatDate da formato visual a una fecha; no realiza conversiones de zona horaria, para las cuales existen funciones específicas como SystemDateToLocalDate()).
En pocas palabras: Aplica formato visual legible a fechas y horas.
Qué hace: Permite utilizar correctamente una URL dinámica procedente de una variable, atributo o campo como destino de un enlace en un email. En emails HTML se utiliza dentro del atributo href de una etiqueta <a> y ayuda a conservar correctamente el click tracking del enlace cuando se implementa de esta forma.
Cuándo la usarías: Al construir enlaces dinámicos en emails donde el destino se calcula mediante AMPscript. (El elemento <a> crea el enlace o botón visual; RedirectTo() proporciona y resuelve el destino dinámico).
En pocas palabras: Ayuda a conservar el click tracking en enlaces construidos con variables dinámicas.
08 · CASOS DE USO REALES Y FLUJO DE DATOS
Para asimilar cómo encajan todos estos elementos, observemos el flujo completo de personalización:
Escenario: Si el campo FirstName contiene datos, queremos normalizarlo con ProperCase() y anteponer un saludo amigable ("¡Hola, Ana!"). Si no contiene datos o es null, queremos usar un fallback natural y cordial como "Estimado/a cliente" sin generar frases redundantes.
%%[ VAR @rawName, @greeting SET @rawName = AttributeValue("FirstName") IF Empty(@rawName) THEN SET @greeting = "Estimado/a cliente" ELSE SET @greeting = Concat("¡Hola, ", ProperCase(@rawName), "!") ENDIF ]%% <!-- Salida HTML --> <h2>%%=v(@greeting)=%%</h2>
Escenario: Evaluamos el importe del carrito y el segmento VIP para asignar un descuento proporcional y un enlace dinámico con tracking.
%%[ VAR @cartTotal, @tier, @discount, @checkoutUrl SET @cartTotal = AttributeValue("CartTotal") SET @tier = AttributeValue("CustomerTier") SET @checkoutUrl = "https://tienda.example.com/checkout?id=cart123" IF @tier == "VIP" AND @cartTotal > 100 THEN SET @discount = 25 ELSEIF @cartTotal > 50 THEN SET @discount = 15 ELSE SET @discount = 5 ENDIF ]%% <!-- Salida HTML con RedirectTo --> <p>Tienes un cupón exclusivo de %%=v(@discount)=%%% de descuento.</p> <a href="%%=RedirectTo(@checkoutUrl)=%%" class="btn-cta">Completar mi compra</a>
09 · REGLAS DE ORO PARA PROGRAMAR EN AMPSCRIPT
Al desarrollar en AMPscript es clave distinguir entre requisitos obligatorios de sintaxis (como usar operadores válidos como == para evaluar condiciones) y buenas prácticas recomendadas que facilitan el mantenimiento y previenen errores en producción:
- Declara las variables con
VAR: Aunque AMPscript permite crear variables sobre la marcha, declararlas explícitamente al inicio hace el código más claro, legible y fácil de mantener. - Utiliza
AttributeValue()para atributos del contexto: Una referencia directa a un atributo que no pueda resolverse (como[NombreCampo]) puede provocar errores durante el renderizado.AttributeValue()ofrece una forma más defensiva de recuperar valores porque devuelvenullcuando no encuentra datos, permitiendo validarlos conEmpty(). - Valida datos importantes con
Empty(): Validar conEmpty()reduce el riesgo de problemas provocados por datos vacíos o nulos al permitir definir valores de respaldo (fallback). - Centraliza la lógica cuando sea posible: Separar la lógica y preparación de datos en un bloque principal al inicio del correo ayuda a mantener el HTML limpio, recordando siempre el orden de renderizado de los componentes.
- Usa
==para comparar igualdad: Recuerda que=asigna un valor, mientras que==comprueba si dos valores son iguales. - Prueba diferentes perfiles en "Preview and Test": Comprueba el comportamiento del correo con perfiles reales que tengan campos vacíos, valores nulos y formatos inusuales.
- Utiliza
RedirectTo()para enlaces dinámicos en emails: Cuando necesites conservar correctamente el click tracking en URLs procedentes de variables o atributos, envuelve la variable dentro del atributohref. - No asumas que los datos vienen limpios: Utiliza funciones según el problema. Por ejemplo,
Trim()elimina espacios en blanco al inicio y al final de un texto, mientras queProperCase()permite normalizar de forma sencilla su capitalización.
10 · COMPRUEBA LO APRENDIDO
Pon a prueba tu comprensión de los conceptos fundamentales antes del desafío práctico:
1. ¿Cuál es la diferencia entre "=" y "==" en AMPscript?
= se utiliza para asignar un valor a una variable (por ejemplo, SET @tier = "VIP"). El operador == se utiliza para comparar si dos valores son iguales dentro de una condición (por ejemplo, IF @tier == "VIP" THEN).
2. ¿Cuándo utilizarías %%[ ]%% y cuándo %%= =%%?
%%[ ... ]%% se utiliza principalmente para bloques de código que ejecutan lógica en el servidor (declarar variables, asignar valores, condicionales). %%= ... =%% se utiliza de forma inline en el HTML para imprimir o renderizar el valor de una variable o función en el mensaje.
3. ¿Por qué es útil combinar AttributeValue() con Empty()?
AttributeValue() recupera el atributo disponible en el contexto retornando null cuando no encuentra datos, y Empty() evalúa si ese resultado está vacío o es nulo para asignar de forma segura un valor por defecto (fallback).
4. ¿Qué diferencia existe entre VAR, SET y v()?
VAR declara la variable (crea la caja con su etiqueta), SET le asigna un valor (guarda un dato dentro de la caja) y v() devuelve el valor almacenado en la variable para mostrarlo en el contenido final.
11 · DESAFÍO ARCADE: TU PRIMER SALUDO DINÁMICO
Crea un bloque de código AMPscript que procese el nombre del suscriptor (FirstName) y su membresía (Tier):
- Recupera
FirstNameyTierde forma segura medianteAttributeValue(). - Si el nombre existe, aplica
ProperCase()y construye el saludo concatenado (ej:Concat("¡Hola, ", ProperCase(@rawName), "!")); si viene vacío o nulo, utiliza el saludo genérico "Estimado/a cliente" conEmpty(). - Evalúa
Tierutilizando comparaciones con==: SiTier == "VIP"asigna un 20% de descuento; siTier == "Gold"asigna un 10%; para cualquier otro caso asigna un 5%. - Imprime el saludo y el porcentaje de descuento en el HTML resultante con
v().
Ver solución comentada
%%[ /* 1. Declaramos todas las variables con VAR */ VAR @rawName, @greeting, @tier, @discountPercent /* 2. Extraemos los campos del contexto de forma segura */ SET @rawName = AttributeValue("FirstName") SET @tier = AttributeValue("Tier") /* 3. Validamos el nombre con Empty() y preparamos el saludo */ IF Empty(@rawName) THEN SET @greeting = "Estimado/a cliente" ELSE SET @greeting = Concat("¡Hola, ", ProperCase(@rawName), "!") ENDIF /* 4. Evaluamos el nivel de membresía con == */ IF @tier == "VIP" THEN SET @discountPercent = 20 ELSEIF @tier == "Gold" THEN SET @discountPercent = 10 ELSE SET @discountPercent = 5 ENDIF ]%% <!-- HTML Renderizado --> <div style="background:#1a1d2e; border:1px solid #00ffff; border-radius:8px; padding:20px; font-family:sans-serif; color:#ffffff;"> <h2 style="color:#00ffff; margin-top:0;">%%=v(@greeting)=%%</h2> <p>Por pertenecer a nuestra comunidad, hoy tienes un beneficio especial:</p> <div style="font-size:24px; font-weight:bold; color:#ff00ff;"> 🎟️ %%=v(@discountPercent)=%%% DE DESCUENTO </div> </div>
Explicación del código: Utilizamos AttributeValue() para capturar los datos de forma defensiva. Con Empty() definimos el fallback de saludo almacenando el resultado en @greeting, formateamos con ProperCase() y aplicamos la escala de descuentos mediante comparaciones estrictas de igualdad con ==.
AMPscript is the proprietary server-side scripting language of Salesforce Marketing Cloud Engagement, designed primarily to personalize content and manipulate data during message and page rendering. With AMPscript, we can generate 1:1 personalized experiences for each contact during message or page rendering.
Analogy: AMPscript works like a restaurant kitchen. The customer doesn't receive the raw recipe or watch the prep work; they only receive the finished, plated dish at their table.
01 · WHAT IS AMPSCRIPT AND WHAT IS IT USED FOR?
AMPscript was purpose-built to address the direct needs of personalized digital messaging in Marketing Cloud. Its core purposes include:
- Injecting dynamic subscriber attributes (first name, loyalty points balance, city, renewal date).
- Executing conditional logic (e.g., showing a specific banner based on customer tier or language preference).
- Querying and joining data stored in Data Extensions using lookup functions.
- Formatting values and dates according to standardized presentation patterns.
- Managing dynamic link tracking via
RedirectTo(), helping preserve click tracking when link targets originate from variables or calculations.
When you need to cross-reference data across tables, AMPscript provides lookup functions such as:
Lookup(): Searches records using a condition and returns the value of a specific column corresponding to a match. When possible, use criteria that clearly identify the specific record you need.LookupRows(): Searches for rows matching a condition and returns a result set of up to 2,000 rows.
| Technology | Primary Focus | Processing Type | Ideal Use Cases |
|---|---|---|---|
| AMPscript | 1:1 Personalization in messages & pages | Render / Send-Time | Dynamic content in emails, SMS, Push, direct lookups, and conditional logic. |
| SSJS (Server-Side JavaScript) | Complex programmatic logic & integrations | Programmatic Execution | JSON parsing, external REST/SOAP API calls, Script Activities in Automation Studio, and advanced CloudPages. |
| SQL (Query Activity) | Massive database segmentation & transformations | Batch Processing | Joining Data Extensions (JOINs), audience segmentation, and preparing data before message dispatch. |
02 · WHERE CAN AMPSCRIPT BE USED?
AMPscript can be used across multiple channels and contexts within Marketing Cloud Engagement:
In Subject lines, Preheaders, HTML blocks, dynamic link attributes via RedirectTo(), and conditional sections.
In MobileConnect for outbound personalized SMS and in MobilePush to personalize push notifications.
In landing pages, preference centers, and form handlers that capture URL query parameters upon web request.
Reusable content or code blocks centralized in Content Builder that can be invoked via ContentBlockByKey() or ContentBlockById().
03 · HOW DOES SALESFORCE PROCESS AN EMAIL WITH AMPSCRIPT?
To understand AMPscript without diving into the deep internal architecture of Salesforce, we can represent the process using the following simplified conceptual flow:
IF/ELSE) and formatting or validation functions execute.%%=v(@name)=%% are substituted with the rendered text or HTML.SET, Set, and set are accepted by the engine). Nevertheless, adhering to a consistent convention is recommended to keep code readable and maintainable.
04 · BASIC SYNTAX AND DELIMITERS
The two primary ways you will write AMPscript most frequently are:
1. Code Blocks: %%[ ... ]%%
%%[ ... ]%% code blocks are primarily used to execute logic, declare variables, prepare data, perform calculations, and evaluate conditions.
Statements such as VAR, SET, and IF do not generate visible content on their own. Typically, inline AMPscript (%%= =%%) is used to output results, although AMPscript also provides functions such as Output(), which allow inserting the result of another function into the rendered content from within a code block.
%%[ /* 1. Variable declaration */ VAR @name, @tier, @discount /* 2. Value assignment */ SET @name = AttributeValue("FirstName") SET @tier = AttributeValue("Tier") /* 3. Conditional logic (comparison using ==) */ IF @tier == "VIP" THEN SET @discount = 20 ELSE SET @discount = 5 ENDIF ]%%
2. Inline Output: %%= ... =%%
Used directly inside HTML markup or plain text to print the value of a variable or function result into that exact position:
<!-- Inline output in HTML body --> <h1>Hello, %%=v(@name)=%%!</h1> <p>Your current status is <strong>%%=v(@tier)=%%</strong>.</p> <p>You have a <span style="color:#00ffff;">%%=v(@discount)=%%% discount</span> available.</p>
<script runat="server" language="ampscript">...</script>, but standard blocks %%[ ]%% and inline tags %%= =%% are the everyday convention in Email Studio and Content Builder.
%%[ ... ]%% to process server-side logic and %%= ... =%% to render dynamic values into your message.
05 · VARIABLES, ASSIGNMENT (=) AND COMPARISON (==)
Understanding how variables are created, assigned, and compared is the foundation of AMPscript development.
1. Declaration with VAR and Assignment with SET
In AMPscript, every variable name begins with the @ character:
VARdeclares the variable (announces to the system that the variable will exist).SETassigns a value to the variable using the=operator.
@firstName).SET takes a value (e.g.,
"Anna") and places it inside that labeled box using the = operator.
Explicitly declaring variables with VAR makes code clearer, helps identify what variables a script utilizes, and significantly improves long-term maintainability.
2. The Critical Difference: Assignment (=) vs Comparison (==)
This is one of the most vital rules for every beginner to master:
Used with SET to store a value into a variable.
SET @tier = "VIP"
Meaning: "Store VIP inside @tier."
Used inside IF to check if two values match.
IF @tier == "VIP" THEN
Meaning: "Check if @tier equals VIP."
= is like placing an item inside a box.== is like checking whether what is inside a box matches a specific value.
3. AMPscript Operators Reference
Below are the exact operators you will write in your scripts:
| Operator | Meaning | Code Example |
|---|---|---|
| == | Equal to | IF @tier == "VIP" THEN |
| != | Not equal to | IF @country != "US" THEN |
| > | Greater than | IF @points > 100 THEN |
| < | Less than | IF @balance < 0 THEN |
| >= | Greater than or equal to | IF @age >= 18 THEN |
| <= | Less than or equal to | IF @attempts <= 3 THEN |
| AND | Logical AND (both must be true) | IF @points > 50 AND @isActive == "True" THEN |
| OR | Logical OR (at least one true) | IF @tier == "VIP" OR @points > 500 THEN |
| NOT | Logical NOT (negates condition) | IF NOT Empty(@name) THEN |
@s_ for strings, @n_ for numbers, and @b_ for booleans. Please note this is an educational convention to assist your learning journey, not an official requirement enforced by Salesforce.
= assigns a value to a variable; == compares two values within an equality condition.
06 · CONTROL FLOW: IF / ELSE CONDITIONAL STATEMENTS
Conditional statements allow you to evaluate business rules and adapt message content based on each subscriber's profile:
IF statement acts like a gatekeeper at an entrance: it evaluates whether a visitor meets an access rule (condition) and decides which path or perk they should receive.
%%[ VAR @segment, @message SET @segment = AttributeValue("CustomerSegment") IF @segment == "Platinum" THEN SET @message = "Exclusive VIP lounge access and unlimited free shipping." ELSEIF @segment == "Gold" THEN SET @message = "Enjoy a 15% discount on your next purchase." ELSE SET @message = "Earn reward points on every order to level up." ENDIF ]%% <!-- In email template --> <div class="promo-box"> <p>%%=v(@message)=%%</p> </div>
07 · ESSENTIAL FUNCTIONS FOR YOUR EVERYDAY WORKFLOW
Key fundamental functions every Marketing Cloud developer must know for defensive personalization:
What it does: Retrieves the attribute value from the available subscriber context. If it finds no data for that attribute, it returns null.
IF Empty(@name) THEN SET @name = "Member" ENDIF
When to use: To safely extract context attributes and combine them defensively with Empty(), gracefully handling data that might be missing.
In a nutshell: Retrieves context attributes returning null when no data is found.
What it does: Returns True when the evaluated value is an empty string "" or null.
When to use: Immediately after AttributeValue() to check if an attribute lacks data and assign a safe fallback default.
In a nutshell: Tests whether a value is blank or null.
What it does: Returns the value stored inside a variable to render it into the content output.
When to use: Anywhere in your HTML markup or text body where you want to output a variable's value.
In a nutshell: Returns the value stored in a variable for printing.
What it does: Joins multiple string fragments, variables, or numbers into a single combined string.
When to use: To construct composite URLs, full names, or dynamic tracking parameters.
In a nutshell: Combines multiple text strings and variables into one.
What it does: Transforms text into proper case format, capitalizing the first letter of each word.
When to use: To normalize the capitalization of subscriber names or text entered in inconsistent casing.
In a nutshell: Capitalizes the first letter of each word in a string.
What it does: Gives display formatting to a date according to standard pattern strings (e.g., "yyyy-MM-dd" or "MM/dd/yyyy").
When to use: To present expiration dates or purchase timestamps in a clean visual format. (Note: FormatDate formats dates visually; it does not perform timezone conversions, for which specialized functions like SystemDateToLocalDate() exist).
In a nutshell: Applies readable visual formatting to dates and times.
What it does: Allows properly utilizing a dynamic URL from a variable, attribute, or field as a link destination in an email. In HTML emails, it is used inside the href attribute of an <a> tag and helps preserve click tracking when implemented this way.
When to use: When creating dynamic links in emails where the target URL is computed via AMPscript. (The <a> element creates the visual link or button; RedirectTo provides and resolves the dynamic destination).
In a nutshell: Helps preserve click tracking on links built with dynamic variables.
08 · REAL-WORLD USE CASES & DATA FLOW
To see how all these concepts connect together, let's examine the end-to-end personalization flow:
Scenario: If FirstName contains data, normalize it with ProperCase() and prefix a cordial greeting ("Hello, Anna!"). If it lacks data or is null, fall back cleanly to "Valued Member" without redundant wording.
%%[ VAR @rawName, @greeting SET @rawName = AttributeValue("FirstName") IF Empty(@rawName) THEN SET @greeting = "Valued Member" ELSE SET @greeting = Concat("Hello, ", ProperCase(@rawName), "!") ENDIF ]%% <!-- HTML Output --> <h2>%%=v(@greeting)=%%</h2>
Scenario: Evaluate cart total and VIP membership to assign a tiered voucher and generate a trackable CTA button.
%%[ VAR @cartTotal, @tier, @discount, @checkoutUrl SET @cartTotal = AttributeValue("CartTotal") SET @tier = AttributeValue("CustomerTier") SET @checkoutUrl = "https://store.example.com/checkout?id=cart123" IF @tier == "VIP" AND @cartTotal > 100 THEN SET @discount = 25 ELSEIF @cartTotal > 50 THEN SET @discount = 15 ELSE SET @discount = 5 ENDIF ]%% <!-- HTML Output with RedirectTo --> <p>You have an exclusive %%=v(@discount)=%%% discount voucher.</p> <a href="%%=RedirectTo(@checkoutUrl)=%%" class="btn-cta">Complete My Order</a>
09 · GOLDEN RULES FOR AMPSCRIPT DEVELOPMENT
When developing in AMPscript, it is vital to distinguish between mandatory syntax requirements (such as using valid comparison operators like == in conditionals) and recommended best practices that improve maintainability and help prevent production errors:
- Declare variables with
VAR: While AMPscript allows on-the-fly variable instantiation, explicitly declaring them at the top makes scripts clean, readable, and easy to maintain. - Use
AttributeValue()for context attributes: A direct attribute reference that cannot be resolved (like[FieldName]) can trigger rendering errors.AttributeValue()provides a defensive way to fetch values by returningnullwhen no data is found, allowing clean validation withEmpty(). - Validate important data with
Empty(): Validating withEmpty()reduces the risk of errors caused by blank or null data by enabling safe fallback defaults. - Centralize logic when possible: Preparing variables in a primary block at the top of your email helps keep HTML clean, while keeping component render order in mind.
- Use
==to compare equality: Remember that=assigns a value, while==checks if two values are equal. - Test multiple subscriber profiles in "Preview and Test": Verify behavior against real contact records with empty attributes, null fields, and edge-case values.
- Use
RedirectTo()for dynamic links in emails: When you need to preserve click tracking on URLs originating from variables or attributes, wrap the variable inside thehrefattribute. - Do not assume input data is clean: Choose helper functions based on the specific issue. For example,
Trim()removes leading and trailing whitespace, whileProperCase()easily normalizes capitalization.
10 · CHECK YOUR UNDERSTANDING
Test your grasp of core AMPscript concepts before tackling the final challenge:
1. What is the difference between "=" and "==" in AMPscript?
= operator is used for assignment to store a value in a variable (e.g., SET @tier = "VIP"). The == operator is used for comparison to test equality in a condition (e.g., IF @tier == "VIP" THEN).
2. When should you use %%[ ]%% vs %%= =%%?
%%[ ... ]%% is primarily used for code blocks that execute logic server-side (declaring variables, assignments, conditionals). %%= ... =%% is used inline in HTML to print/render the value of a variable or function in the message.
3. Why is combining AttributeValue() with Empty() a best practice?
AttributeValue() retrieves the context attribute returning null when no data is found, and Empty() tests whether that result is blank or null so you can apply a safe fallback default.
4. What is the difference between VAR, SET, and v()?
VAR declares the variable (creates the labeled box), SET assigns a value (places data into the box), and v() returns the stored value of a variable to render it in the final output.
11 · ARCADE CHALLENGE: YOUR FIRST DYNAMIC GREETING
Create an AMPscript block that processes subscriber name (FirstName) and loyalty tier (Tier):
- Safely extract
FirstNameandTierusingAttributeValue(). - If the name exists, format it with
ProperCase()and build the concatenated greeting (e.g.,Concat("Hello, ", ProperCase(@rawName), "!")); if blank or null, use the fallback "Valued Member" withEmpty(). - Evaluate
Tierusing strict equality with==: IfTier == "VIP", assign 20% off; ifTier == "Gold", assign 10%; otherwise, assign 5%. - Output the personalized greeting and discount percentage in the HTML using
v().
View full solution
%%[ /* 1. Declare all variables with VAR */ VAR @rawName, @greeting, @tier, @discountPercent /* 2. Safely extract subscriber context data */ SET @rawName = AttributeValue("FirstName") SET @tier = AttributeValue("Tier") /* 3. Validate name with Empty() and build greeting */ IF Empty(@rawName) THEN SET @greeting = "Valued Member" ELSE SET @greeting = Concat("Hello, ", ProperCase(@rawName), "!") ENDIF /* 4. Evaluate membership tier using == */ IF @tier == "VIP" THEN SET @discountPercent = 20 ELSEIF @tier == "Gold" THEN SET @discountPercent = 10 ELSE SET @discountPercent = 5 ENDIF ]%% <!-- Rendered HTML --> <div style="background:#1a1d2e; border:1px solid #00ffff; border-radius:8px; padding:20px; font-family:sans-serif; color:#ffffff;"> <h2 style="color:#00ffff; margin-top:0;">%%=v(@greeting)=%%</h2> <p>As a valued member of our community, you have a special perk:</p> <div style="font-size:24px; font-weight:bold; color:#ff00ff;"> 🎟️ %%=v(@discountPercent)=%%% OFF </div> </div>
Breakdown: We use AttributeValue() to retrieve attributes defensively. With Empty() we provide a safe greeting fallback stored inside @greeting, format with ProperCase(), and evaluate @tier using strict equality == comparisons.