AMPscript IF Statement returning variable as empty

609 Views Asked by At

I am running into an issue in AMPscript where the following IF statement is returning my variable @shippingVendor as nothing when I call it. (Tracking Number is from data extension)

Assuming @trackingNumber = 23456

%%[
var @shippingVendor

IF Substring(@trackingNumber, 1, 1) == "2" THEN
   SET @shippingVendor = "https://www.nzpost.co.nz/tools/tracking/item/"
  ELSEIF Substring(@trackingNumber, 1, 2) == "T1" THEN
   SET @shippingVendor = "https://www.mainfreight.com/en-nz/tracking?trackingnumber="
  ELSEIF Substring(@trackingNumber, 1, 3) == "TP1" THEN
   SET @shippingVendor = "https://www.mytoll.com/?"
ENDIF
]%%

I would expect %%=v(@shippingVendor)=%% to return https://www.nzpost.co.nz/tools/tracking/item/ - however instead it returns nothing...can I please check if I am doing anything wrong?

Fairly new to AMPscript so would love your help on this - thanks in advance!

1

There are 1 best solutions below

0
On

It's dangerous to do substring in AMPscript without checking for existence and length. I'd also set a default value for the shipping vendor URL.

%%[

set @trackingNumber = 23456

set @shippingVendor = "DEFAULVENDORURLHERE"

if not empty(@trackingNumber) then

   IF length(@trackingNumber) >= 1 and Substring(@trackingNumber, 1, 1) == "2" THEN

      SET @shippingVendor = "https://www.nzpost.co.nz/tools/tracking/item/"

   ELSEIF length(@trackingNumber) >= 2 and Substring(@trackingNumber, 1, 2) == "T1" THEN

      SET @shippingVendor = "https://www.mainfreight.com/en-nz/tracking?trackingnumber="

   ELSEIF length(@trackingNumber) >= 3 and Substring(@trackingNumber, 1, 3) == "TP1" THEN

      SET @shippingVendor = "https://www.mytoll.com/?"
      
   ENDIF

endif

]%%
shippingVendor: %%=v(@shippingVendor)=%%

Output:

shippingVendor: https://www.nzpost.co.nz/tools/tracking/item/

Demo: https://mcsnippets.herokuapp.com/s/eiSqyIcb