wvpv
3/21/2016 - 2:44 PM

SFMC SSJS Delete Rows from a Data Extension

SFMC SSJS Delete Rows from a Data Extension

<script runat="server">

Platform.Load("core", "1.1.1");

function pruneRows () {

  var DERowKeys = DataExtension.Init("DEofRowKeys");
  var DERowKeyRows = DERowKeys.Rows.Lookup(["ProcessedFlag"], [0], 50, "RowDate");

  var returnString = "";
  var totalDelCount = 0;

  for (var i in DERowKeyRows) {

     var RowKey = DERowKeyRows[i].RowKey;
     var RowDate = DERowKeyRows[i].RowDate;

     returnString += "<br>" + RowKey;
     returnString += ", " + RowDate;

     var delCount = 0;
     var action = "";
     var begin = (new Date()).getTime();

     var sl = DataExtension.Init("DataExtensionToPrune");

     try {

       delCount += sl.Rows.Remove(["RowKey"], [RowKey]);
       totalDelCount += delCount;
       action = "delete";           
       returnString += ", " + delCount;

     } catch (e) {

       action = "error";

     }

     var end = (new Date()).getTime();
     var duration = (end-begin).toString() + 'ms ';

     // update row as processed
     if (action != "error") {

        var updateCount = DERowKeys.Rows.Update({"ProcessedFlag":1,"RowsDeleted":delCount, "Duration":duration, "Action":action}, ["RowKey"], [RowKey]);

     }

  }

  returnString += "<br>total deleted in batch: " + totalDelCount;

  return returnString;
}

</script>