Skip to main content

SFMC AMPscript Loop

What is a Loop?

A loop is a programming structure that executes the same block of code repeatedly until a specified condition is met.

Why Do We Need Loops?

Without loops:

  • More code

  • Difficult maintenance

  • High chances of errors

With loops:

  • Less code

  • Dynamic processing

  • Easy maintenance

  • Better scalability

Loop Structure

%%[ FOR @i=1 to 10 DO ]%% %%=v(@i)=%%<br> %%[NEXT @i ]%%

Components

Component

Meaning

FOR

Start Loop

@i

Loop Variable

1

Starting Value

5

Ending Value

DO

Begin Execution

NEXT @i

Increment Variable



Execution:

Step 1

@i = 1

1 <= 5

TRUE

Execute Code


Step 2

@i = 2

2 <= 5

TRUE

Execute Code


Step 3

@i = 3

3 <= 5

TRUE

Execute Code


Step 4

@i = 4

4 <= 5

TRUE

Execute Code


Step 5

@i = 5

5 <= 5

TRUE

Execute Code


Step 6

@i = 6

6 <= 6

TRUE

Execute Code


Step 7

@i = 7

7 <= 7

TRUE

Execute Code


Step 8

@i = 8

8 <= 8

TRUE

Execute Code


Step 9

@i = 9

9 <= 9

TRUE

Execute Code


Step 10

@i = 10

10 <= 10

TRUE

Execute Code


Step 11

@i = 11

11 <= 11

FALSE

STOP


Loop Flow Diagram

Start

Initialize Variable

Check Condition

Execute Code

NEXT

Condition True?

Yes → Repeat

No → Stop


Example 1: Print 1 - 10

%%[ FOR @i=1 TO 10 DO ]%% Coupon:%%=v(@i)=%% <br> %%[ NEXT @i ]%%




Business Use:

  • Generate coupon numbers

  • Display rankings

  • Create dynamic counters


Example 2: Print 10 to 1

Business Use:

  • Countdown Campaign

  • Sale Expiry Timer

%%[
FOR @i=10 DOWNTO 1 DO
]%%

Countdown:%%=v(@i)=%% <br>

%%[
NEXT @i
]%%









Conditional Logic with Loops

Equal To (Add IF Condition)

%%[ FOR @i=1 TO 10 DO ]%% Discount: %%=v(@i)=%%<br> %%[ IF @i==5 THEN ]%% 20% Discount <br> %%[ ENDIF <br> NEXT @i ]%%




Not Equal To

IF @status != "Inactive" THEN


Use Case:

  • Exclude inactive users

%%[ Var @Segment, @Message SET @Segment = AttributeValue ("Segment") ]%% %%[ IF @Segment!="Inactive" THEN ]%% Welcome Back %%[ ENDIF ]%%






Greater Than

%%[ IF @PointsBalance >1000 THEN ]%% VIP Offer %%[ ENDIF ]%%



Less Than

%%[ IF @PointsBalance <900 THEN ]%% Welcome %%[ ENDIF]%%

Greater Than or Equal

%%[ Var @Message, @PointsBalance SET @PointsBalance = AttributeValue ("PointsBalance") ]%% %%[ IF @PointsBalance >=1000 THEN ]%% VIP Offer %%[ ENDIF ]%%


Less Than or Equal

%%[
Var @Message, @PointsBalance

SET @PointsBalance = AttributeValue ("PointsBalance")
]%%

%%[
IF @PointsBalance <=500 THEN
]%%

Student Discount 20%

%%[
ENDIF
]%%

AND Operator

%%[
Var @Message, @PointsBalance, @Segment

SET @PointsBalance = AttributeValue ("PointsBalance")
SET @Segment = AttributeValue ("Segment")
]%%

%%[
IF @PointsBalance > 1000 AND @Segment == "Active" THEN
]%%

High Value Customer

%%[
ENDIF
]%%

OR Operator

%%[
Var @Message, @PointsBalance, @Segment, @City

SET @PointsBalance = AttributeValue ("PointsBalance")
SET @Segment = AttributeValue ("Segment")
SET @City = AttributeVAlue ("City")
]%%

%%[
IF @City == "Bangalore" OR @City == "Mumbai" THEN
]%%

Welcome Dear %%=v(@City)=%%

%%[
ENDIF
]%%

Even Number Logic

Use Case:

  • Alternate Layout Design

  • Row Grouping

%%[ FOR @i = 1 TO 10 DO ]%% %%[ IF MOD(@i,2) == 0 THEN ]%% %%=v(@i)=%%<br> %%[ ENDIF Next @i ]%%


Odd Number Logic

Use Case:
  • Alternate Content Blocks

%%[ FOR @i = 1 TO 10 DO ]%% %%[ IF MOD(@i,2) == 1 THEN ]%% %%=v(@i)=%%<br> %%[ ENDIF Next @i ]%%

IF ELSE Example

Business Use:

  • Personalized Product Recommendations


%%[SET @Gender = AttributeValue ("Gender")]%% %%[IF @Gender == "Male" THEN]%% Men Collection %%[ ELSE ]%% Women Collection %%[ ENDIF ]%%


Most Important SFMC Loop Use Case


Flow Diagram:

LookupRows()

RowCount()

FOR Loop

Row()

Field()

Output()

Loop Through Data Extension

Data Extension:

Product

Laptop

Mobile

Watch



%%[ SET @rows = LookupRows("ProductCatalog","Category","Electronics") SET @count = RowCount(@rows) FOR @i = 1 TO @count DO SET @row = Row(@rows,@i) SET @ProductName = Field(@row,"ProductName") OUTPUT(CONCAT(@ProductName,"<br>")) NEXT @i ]%%

Functions Used with Loops

Function

Purpose

LookupRows()

Fetch Records

RowCount()

Count Records

Row()

Retrieve Row

Field()

Retrieve Column Value

MOD()

Even/Odd Logic

Output()

Display Value

Concat()

Concatenate Strings

Comments

Popular posts from this blog

A/B Testing

Confluence link 1:  https://elearningit24.atlassian.net/wiki/external/MzA3YWUxNjI3YzBkNGZiZmFlZTc1ZGIzYmU1ZmM1MmQ   What is A/B Testing? A/B testing, also known as split testing , is a controlled experiment where two versions of a webpage, email, ad, or any digital asset are tested against each other to determine which one performs better. Why? Higher open rates Better Engagement Increased Sales and Lead conversion Reduced unsubscribed rates Date Driven- No assumption & Proven Results Test Type Subject Line Email Content Area From Name Send Date & Time Pre Header   Email Test Template: Friendly and Personalised Straight to the point & Action Oriented Confluence Link 2:  https://elearningit24.atlassian.net/wiki/external/NDk0Zjg0ODk3YjAwNDI5ZjkxOTVmMTAxNTQ3ZjlhNmQ Subject Line A/B Test: A/B Testing Use Case: Optimizing Email Subject Lines for Higher Open Rates Scenario- Subject Line: A company wants to increase the open rates of its promotional emails in Sa...

Email Marketing Campaings

Use Cases of Standard Data Extensions 1. Customer Data Storage Scenario : A retail business wants to store customer information, such as names, email addresses, and purchase history, for email marketing campaigns. Solution : Use a standard data extension to store and manage customer data securely and efficiently. Data Extension Structure Field Name Data Type Length Required Primary Key SubscriberKey Text 50 Yes Yes FirstName Text 50 Yes No LastName Text 50 Yes No EmailAddress EmailAddress N/A Yes No PurchaseHistory Decimal N/A No No Sample Records SubscriberKey FirstName LastName EmailAddress PurchaseHistory 001 John Doe john.doe@example.com 1500.50 002 Jane Smith jane.smith@example.com 200.00 https://mc.s8.exacttarget.com/cloud/#app/Email/C12/Default.aspx?entityType=none&entityID=0&ks=ks%23Subscribers

SQl Query

  Workflow: Journey Builder> Automation Studio> New Automation Enter Query: Drag and drop Schedule in  Start with a Starting Source and the SQL Query> Choose Query> Create New Query Activity> Name your file and add your query (Field name thats part of the DE you create separately- Example: FirstName, LastName, Subscriber Key) Create a new DE in Email Studio with the query field> Select The test DE which was created: Select Target DE and Save & Run Workflow: Select All Activities and Run Workflow: Activity Details: Run Completed with updated DE Edit/ add another query: Copy Source DE and create a new DE with same fields that we are running in SQL: Run the updated SQL Query added Activity and DE updated with Records: Completed Status: Received error: When the Query field and the DE created field does not match When an existing Query is being run, if we try to run another query Fixed the error by matching same field Waiting for existing query to complete