Inicio Home / AMPscript / Artículo Article
AMPSCRIPT 🟢 Beginner

Introducción a AMPscript: Guía Completa de Fundamentos

Introduction to AMPscript: Complete Fundamentals Guide

Aprende qué es AMPscript, dónde se ejecuta en SFMC Engagement, cómo procesa Salesforce cada mensaje, delimitadores, variables, condicionales, funciones esenciales y buenas prácticas para personalización 1:1.

Learn what AMPscript is, where it executes in SFMC Engagement, how Salesforce processes each message, delimiters, variables, conditionals, essential functions, and best practices for 1:1 personalization.

📌 ALCANCE DE ESTA GUÍA
Este artículo se centra principalmente en AMPscript dentro de Salesforce Marketing Cloud Engagement. Marketing Cloud Next también incorpora capacidades relacionadas con AMPscript, pero la disponibilidad y el comportamiento de determinadas funciones puede ser diferente.

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.

📌 CONCEPTO CLAVE · ¿POR QUÉ EXISTE AMPSCRIPT?
A diferencia de lenguajes del lado del cliente (client-side) como JavaScript en el navegador, AMPscript es un lenguaje del lado del servidor (server-side). AMPscript se ejecuta en los servidores de Salesforce. En mensajes, se evalúa durante su renderizado o proceso de envío; en CloudPages o Landing Pages, se ejecuta cuando la página es solicitada y renderizada. El destinatario final nunca ve el código fuente; únicamente recibe el HTML o texto plano resultante ya personalizado con sus datos.

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.
🎯 LO QUE APRENDERÁS EN ESTA GUÍA
✅ 1. Qué es AMPscript y para qué sirve
✅ 2. Dónde se ejecuta en SFMC
✅ 3. Cómo procesa Salesforce el contenido
✅ 4. Sintaxis y delimitadores clave
✅ 5. Variables y asignación vs comparación
✅ 6. Condicionales y operadores (= vs ==)
✅ 7. Funciones esenciales del día a día
✅ 8. Casos de uso reales con flujo de datos
✅ 9. Buenas prácticas y reglas de oro
✅ 10. Autoevaluación y Desafío Arcade

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.
💡 CONCEPTOS RELACIONADOS · DATA EXTENSIONS Y BÚSQUEDAS
Una Data Extension (DE) es una estructura tabular de Marketing Cloud donde almacenamos registros y atributos. Para imaginarla fácilmente, piensa en una hoja de Excel formada por filas y columnas.

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.
⚔️ CUÁNDO USAR AMPSCRIPT VS SSJS VS SQL EN SFMC
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.
💡 EN POCAS PALABRAS
AMPscript permite transformar datos en contenido altamente personalizado durante el renderizado de tus mensajes.

02 · ¿DÓNDE SE PUEDE USAR AMPSCRIPT?

AMPscript puede utilizarse en múltiples canales y contextos de Marketing Cloud Engagement:

CANAL 01
📧 Email Studio & Content Builder

En líneas de asunto (Subject lines), Preheaders, bloques HTML, atributos de enlaces dinámicos con RedirectTo() y bloques condicionales.

CANAL 02
📱 Mobile Studio (SMS & Push)

En MobileConnect para enviar SMS personalizados y en MobilePush para personalizar notificaciones push.

CANAL 03
🌐 CloudPages & Web

En Landing Pages, centros de preferencias de suscripción y formularios que capturan parámetros de URL al momento de la solicitud web.

CANAL 04
📦 Content Blocks Reutilizables

Bloques de contenido o código reutilizable centralizados en Content Builder que pueden invocarse mediante ContentBlockByKey() o ContentBlockById().

💡 EN POCAS PALABRAS
Puedes utilizar AMPscript en emails, SMS, Push, CloudPages y bloques modulares para personalizar cualquier punto de contacto.

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:

🔄 FLUJO CONCEPTUAL DE PROCESAMIENTO
PASO 1
Salesforce obtiene el contexto del contacto: Se toma el registro correspondiente al suscriptor actual desde la Data Extension o lista de envío de origen.
PASO 2
AMPscript accede a los datos disponibles: El motor lee el código, inicializa variables y recupera atributos o datos relacionados.
PASO 3
Se evalúan funciones y condiciones: Se ejecutan las estructuras lógicas (IF/ELSE) y las funciones de formateo o validación.
PASO 4
Se genera el contenido personalizado: Las salidas inline como %%=v(@nombre)=%% se sustituyen por el texto o HTML resultante.
PASO 5
Salesforce produce el mensaje final: Se genera el mensaje final personalizado listo para ser despachado al destinatario.
💡 PRO TIP · ORDEN DE PROCESAMIENTO ENTRE COMPONENTES DE EMAIL
Marketing Cloud procesa los componentes del email en este orden: Preheader → HTML Body → Text Body → Subject Line. Por ello, una variable definida anteriormente en el proceso puede estar disponible en componentes procesados después (por ejemplo, preparar una variable en el cuerpo HTML para reutilizarla en el asunto).
📌 PRECISIÓN · CASE SENSITIVITY
Las palabras clave y los nombres de funciones de AMPscript no distinguen entre mayúsculas y minúsculas (por ejemplo, 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.
💡 EN POCAS PALABRAS
Salesforce ejecuta AMPscript en sus servidores para ensamblar y personalizar cada mensaje individual antes de despacharlo.

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.

AMPscript · 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:

HTML + AMPscript Inline
<!-- 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>
📌 NOTA DE SINTAXIS ADICIONAL
Salesforce también admite sintaxis basada en script tags como <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.
💡 EN POCAS PALABRAS
Usa %%[ ... ]%% 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 @:

  • VAR declara la variable (informa al sistema que la variable existirá).
  • SET asigna un valor a la variable utilizando el operador =.
📦 ANALOGÍA DE LAS CAJAS
VAR crea una caja vacía y le coloca una etiqueta con su nombre (ej: @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:

= · ASIGNACIÓN

Se utiliza con SET para guardar un valor dentro de una variable.

SET @tier = "VIP"

Significa: "Guarda VIP dentro de @tier."

== · COMPARACIÓN DE IGUALDAD

Se utiliza dentro de IF para comprobar si dos valores son iguales.

IF @tier == "VIP" THEN

Significa: "Comprueba si @tier contiene VIP."

💡 ANALOGÍA
= 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:

⚙️ OPERADORES DE COMPARACIÓN Y LÓGICOS
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
💡 CONVENCIÓN EDUCATIVA DE MARKETING CLOUD ARCADE
Para mantener los proyectos limpios y fáciles de leer, en Marketing Cloud Arcade utilizaremos a menudo prefijos como @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.
💡 EN POCAS PALABRAS
= 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:

🚪 ANALOGÍA DEL PORTERO
Una estructura 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.
AMPscript · IF / ELSEIF / ELSE
%%[
  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>
💡 EN POCAS PALABRAS
Los condicionales evalúan reglas de negocio para mostrar el contenido adecuado a cada suscriptor.

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:

AttributeValue("Campo")

Qué hace: Recupera el valor de un atributo disponible en el contexto del suscriptor. Si no encuentra datos para ese atributo, devuelve null.

SET @nombre = AttributeValue("FirstName")
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.

Empty(@variable)

Qué hace: Devuelve True cuando el valor evaluado está vacío (cadena vacía "") o es null.

IF Empty(@nombre) THEN SET @nombre = "Cliente" ENDIF

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.

v(@variable)

Qué hace: Devuelve el valor almacenado en una variable para mostrarlo dentro del contenido.

<h1>Hola, %%=v(@nombre)=%%</h1>

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.

Concat("Texto1", @var, "Texto2")

Qué hace: Une múltiples cadenas de texto, variables o números en un solo string resultante.

SET @completo = Concat(@nombre, " ", @apellido)

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.

ProperCase(@variable)

Qué hace: Transforma un texto a formato proper case, capitalizando la primera letra de cada palabra.

SET @nombreLimpio = ProperCase(@nombreCrudo)

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.

FormatDate(Fecha, "Patrón")

Qué hace: Da formato de presentación a una fecha según patrones estándar (ej: "yyyy-MM-dd" o "dd/MM/yyyy").

SET @hoy = FormatDate(Now(), "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.

RedirectTo(@urlDinamica)

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.

<a href="%%=RedirectTo(@checkoutUrl)=%%">Completar compra</a>

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.

💡 EN POCAS PALABRAS
Estas funciones constituyen la caja de herramientas esencial para recuperar, sanear, formatear e imprimir datos de forma segura.

08 · CASOS DE USO REALES Y FLUJO DE DATOS

Para asimilar cómo encajan todos estos elementos, observemos el flujo completo de personalización:

DATOS DE ENTRADA  →  AMPSCRIPT  →  DECISIÓN CONDICIONAL  →  CONTENIDO RESULTANTE
✔️ CASO 1: Saludo personalizado con fallback defensivo

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.

AMPscript · Saludo Defensivo
%%[
  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>
✔️ CASO 2: Oferta escalonada en Carrito Abandonado

Escenario: Evaluamos el importe del carrito y el segmento VIP para asignar un descuento proporcional y un enlace dinámico con tracking.

AMPscript · Lógica de Carrito
%%[
  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>
💡 EN POCAS PALABRAS
Combinar recuperación defensiva de datos, validación con Empty() y condicionales ayuda a crear experiencias personalizadas robustas.

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:

  1. 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.
  2. 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 devuelve null cuando no encuentra datos, permitiendo validarlos con Empty().
  3. Valida datos importantes con Empty(): Validar con Empty() reduce el riesgo de problemas provocados por datos vacíos o nulos al permitir definir valores de respaldo (fallback).
  4. 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.
  5. Usa == para comparar igualdad: Recuerda que = asigna un valor, mientras que == comprueba si dos valores son iguales.
  6. 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.
  7. 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 atributo href.
  8. 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 que ProperCase() permite normalizar de forma sencilla su capitalización.
💡 EN POCAS PALABRAS
Programar de forma defensiva y separar lógica de presentación facilita el mantenimiento y ayuda a prevenir fallos en envíos masivos.

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?
Respuesta: El operador = 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 %%= =%%?
Respuesta: %%[ ... ]%% 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()?
Respuesta: 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()?
Respuesta: 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.
💡 EN POCAS PALABRAS
VAR crea la variable, SET le asigna un valor, los condicionales evalúan reglas con == y v() muestra el resultado.

11 · DESAFÍO ARCADE: TU PRIMER SALUDO DINÁMICO

🎮
MISIÓN: Saludo Personalizado con Descuento Dinámico

Crea un bloque de código AMPscript que procese el nombre del suscriptor (FirstName) y su membresía (Tier):

  • Recupera FirstName y Tier de forma segura mediante AttributeValue().
  • 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" con Empty().
  • Evalúa Tier utilizando comparaciones con ==: Si Tier == "VIP" asigna un 20% de descuento; si Tier == "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
Solución Completa · AMPscript
%%[
  /* 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 ==.

📌 SCOPE OF THIS GUIDE
This article focuses primarily on AMPscript within Salesforce Marketing Cloud Engagement. Marketing Cloud Next also incorporates AMPscript-related capabilities, but the availability and behavior of specific functions may differ.

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.

📌 KEY CONCEPT · WHY DOES AMPSCRIPT EXIST?
Unlike client-side languages like JavaScript in a web browser, AMPscript is a server-side language. AMPscript executes on Salesforce servers. In messages, it is evaluated during rendering or the send process; in CloudPages or Landing Pages, it executes when the page is requested and rendered. The end recipient never sees the AMPscript source code; they only receive the final rendered HTML or plain text personalized with their data.

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.
🎯 WHAT YOU WILL LEARN IN THIS GUIDE
✅ 1. What AMPscript is & what it is used for
✅ 2. Where it executes in SFMC
✅ 3. How Salesforce processes content
✅ 4. Core syntax & delimiters
✅ 5. Variables & assignment vs comparison
✅ 6. Conditionals & operators (= vs ==)
✅ 7. Essential day-to-day functions
✅ 8. Real-world use cases with data flow
✅ 9. Best practices & golden rules
✅ 10. Self-assessment & Arcade Challenge

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.
💡 RELATED CONCEPTS · DATA EXTENSIONS & LOOKUPS
A Data Extension (DE) is a tabular structure in Marketing Cloud where records and attributes are stored. To visualize it easily, think of an Excel spreadsheet with rows and columns.

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.
⚔️ WHEN TO USE AMPSCRIPT VS SSJS VS SQL IN SFMC
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.
💡 IN A NUTSHELL
AMPscript transforms raw subscriber data into highly personalized content during message rendering.

02 · WHERE CAN AMPSCRIPT BE USED?

AMPscript can be used across multiple channels and contexts within Marketing Cloud Engagement:

CHANNEL 01
📧 Email Studio & Content Builder

In Subject lines, Preheaders, HTML blocks, dynamic link attributes via RedirectTo(), and conditional sections.

CHANNEL 02
📱 Mobile Studio (SMS & Push)

In MobileConnect for outbound personalized SMS and in MobilePush to personalize push notifications.

CHANNEL 03
🌐 CloudPages & Web

In landing pages, preference centers, and form handlers that capture URL query parameters upon web request.

CHANNEL 04
📦 Reusable Content Blocks

Reusable content or code blocks centralized in Content Builder that can be invoked via ContentBlockByKey() or ContentBlockById().

💡 IN A NUTSHELL
You can leverage AMPscript across emails, SMS, Push, CloudPages, and modular blocks to personalize every customer touchpoint.

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:

🔄 CONCEPTUAL PROCESSING PIPELINE
STEP 1
Salesforce loads subscriber context: The current subscriber record is loaded from the source Data Extension or send list.
STEP 2
AMPscript accesses available data: The engine parses the code, initializes variables, and retrieves attributes or related records.
STEP 3
Functions and conditions are evaluated: Logical structures (IF/ELSE) and formatting or validation functions execute.
STEP 4
Personalized content is generated: Inline output tags like %%=v(@name)=%% are substituted with the rendered text or HTML.
STEP 5
Salesforce produces final message: The finalized personalized message is produced for delivery to the recipient.
💡 PRO TIP · EMAIL COMPONENT PROCESSING ORDER
Marketing Cloud processes email components in this order: Preheader → HTML Body → Text Body → Subject Line. Because of this, a variable defined earlier in the process can be available in components processed afterward (for example, setting a variable in the HTML body to reuse it in the subject line).
📌 PRECISION · CASE SENSITIVITY
Keywords and function names in AMPscript are case-insensitive (for example, SET, Set, and set are accepted by the engine). Nevertheless, adhering to a consistent convention is recommended to keep code readable and maintainable.
💡 IN A NUTSHELL
Salesforce executes AMPscript server-side to assemble and tailor each individual message before delivery.

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.

AMPscript · 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:

HTML + Inline AMPscript
<!-- 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>
📌 ADDITIONAL SYNTAX NOTE
Salesforce also supports script-tag based syntax like <script runat="server" language="ampscript">...</script>, but standard blocks %%[ ]%% and inline tags %%= =%% are the everyday convention in Email Studio and Content Builder.
💡 IN A NUTSHELL
Use %%[ ... ]%% 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:

  • VAR declares the variable (announces to the system that the variable will exist).
  • SET assigns a value to the variable using the = operator.
📦 THE BOX ANALOGY
VAR creates an empty box and places a label on it (e.g., @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:

= · ASSIGNMENT

Used with SET to store a value into a variable.

SET @tier = "VIP"

Meaning: "Store VIP inside @tier."

== · EQUALITY COMPARISON

Used inside IF to check if two values match.

IF @tier == "VIP" THEN

Meaning: "Check if @tier equals VIP."

💡 ANALOGY
= 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:

⚙️ COMPARISON & LOGICAL OPERATORS
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
💡 MARKETING CLOUD ARCADE EDUCATIONAL CONVENTION
To maintain structured and readable scripts, in Marketing Cloud Arcade we frequently adopt prefixes such as @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.
💡 IN A NUTSHELL
= 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:

🚪 THE GATEKEEPER ANALOGY
An 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.
AMPscript · IF / ELSEIF / ELSE
%%[
  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>
💡 IN A NUTSHELL
Conditionals evaluate business logic to deliver tailored content to every recipient.

07 · ESSENTIAL FUNCTIONS FOR YOUR EVERYDAY WORKFLOW

Key fundamental functions every Marketing Cloud developer must know for defensive personalization:

AttributeValue("Field")

What it does: Retrieves the attribute value from the available subscriber context. If it finds no data for that attribute, it returns null.

SET @name = AttributeValue("FirstName")
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.

Empty(@var)

What it does: Returns True when the evaluated value is an empty string "" or null.

IF Empty(@name) THEN SET @name = "Member" ENDIF

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.

v(@var)

What it does: Returns the value stored inside a variable to render it into the content output.

<h1>Hello, %%=v(@name)=%%</h1>

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.

Concat("Text1", @var, "Text2")

What it does: Joins multiple string fragments, variables, or numbers into a single combined string.

SET @fullName = Concat(@first, " ", @last)

When to use: To construct composite URLs, full names, or dynamic tracking parameters.

In a nutshell: Combines multiple text strings and variables into one.

ProperCase(@var)

What it does: Transforms text into proper case format, capitalizing the first letter of each word.

SET @cleanName = ProperCase(@rawName)

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.

FormatDate(Date, "Pattern")

What it does: Gives display formatting to a date according to standard pattern strings (e.g., "yyyy-MM-dd" or "MM/dd/yyyy").

SET @today = FormatDate(Now(), "yyyy-MM-dd")

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.

RedirectTo(@dynamicUrl)

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.

<a href="%%=RedirectTo(@checkoutUrl)=%%">Complete Purchase</a>

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.

💡 IN A NUTSHELL
These functions constitute the essential toolkit for safely retrieving, sanitizing, formatting, and rendering dynamic subscriber data.

08 · REAL-WORLD USE CASES & DATA FLOW

To see how all these concepts connect together, let's examine the end-to-end personalization flow:

INPUT DATA  →  AMPSCRIPT  →  CONDITIONAL DECISION  →  OUTPUT CONTENT
✔️ CASE 1: Dynamic greeting with defensive fallback

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.

AMPscript · Defensive Greeting
%%[
  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>
✔️ CASE 2: Tiered offers in an Abandoned Cart campaign

Scenario: Evaluate cart total and VIP membership to assign a tiered voucher and generate a trackable CTA button.

AMPscript · Cart Logic
%%[
  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>
💡 IN A NUTSHELL
Combining defensive data extraction, Empty() validation, and conditionals helps create robust personalized customer experiences.

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:

  1. 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.
  2. 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 returning null when no data is found, allowing clean validation with Empty().
  3. Validate important data with Empty(): Validating with Empty() reduces the risk of errors caused by blank or null data by enabling safe fallback defaults.
  4. 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.
  5. Use == to compare equality: Remember that = assigns a value, while == checks if two values are equal.
  6. Test multiple subscriber profiles in "Preview and Test": Verify behavior against real contact records with empty attributes, null fields, and edge-case values.
  7. 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 the href attribute.
  8. Do not assume input data is clean: Choose helper functions based on the specific issue. For example, Trim() removes leading and trailing whitespace, while ProperCase() easily normalizes capitalization.
💡 IN A NUTSHELL
Defensive programming and clean separation of logic from HTML presentation improve maintainability and help prevent issues during mass sends.

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?
Answer: The = 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 %%= =%%?
Answer: %%[ ... ]%% 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?
Answer: 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()?
Answer: 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.
💡 IN A NUTSHELL
VAR creates the variable, SET assigns a value, conditionals evaluate rules using ==, and v() displays the result.

11 · ARCADE CHALLENGE: YOUR FIRST DYNAMIC GREETING

🎮
MISSION: Personalized Greeting with Dynamic Discount

Create an AMPscript block that processes subscriber name (FirstName) and loyalty tier (Tier):

  • Safely extract FirstName and Tier using AttributeValue().
  • 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" with Empty().
  • Evaluate Tier using strict equality with ==: If Tier == "VIP", assign 20% off; if Tier == "Gold", assign 10%; otherwise, assign 5%.
  • Output the personalized greeting and discount percentage in the HTML using v().
View full solution
Full Solution · AMPscript
%%[
  /* 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.

◀ Anterior
◀ Previous
¿Qué es Marketing Cloud Engagement?
What is Marketing Cloud Engagement?
ESC
ARTÍCULOS RECIENTES
🕹️ ¡CÓDIGO KONAMI! +9999 XP DESBLOQUEADOS