Compile function SQL_Delete_MV(Connection, TableName, Keys, MvFieldsList)

/*****************************************************************************\
	Writes an associated set of multie-valued fields to the given table.
	
	History
	-------
	04/14/2010    KRF   Original Programmer
\*****************************************************************************/

$insert Microsoft_Ado_Equates

If Assigned(Connection) else Connection = 0
If Assigned(TableName) else TableName = ""
If Assigned(Keys) else Keys = ""
If Assigned(MvFieldsList) else MvFieldsList = ""

Declare subroutine SRP_Com
Declare function SRP_Com, SQL_Write, SRP_Rotate_Array
Ans = ""

// Rotate the MvFields array so we can quickly get the data we want
MvFieldsArray = SRP_Rotate_Array(MvFieldsList, @RM, @FM)

// Get the data names and rows
DataNames = MvFieldsArray[1, @RM]
DataCols = MvFieldsArray[Col2() + 1, @RM]
DataRows = SRP_Rotate_Array(DataCols)
LenDataRows = Len(DataRows)
Convert @FM to @VM in DataNames
       
// Process each data row
iDataRow = 0
DataRowPos = 1
Loop
   
    // Extract the data ([] is faster than <>)
    DataRow = DataRows[DataRowPos, @FM]
    DataRowPos = Col2() + 1
    iDataRow += 1
    
    // Add the MV_NO key part
    MvKeys = Keys:@FM:"MV_NO":@VM:iDataRow
    
    // Get the data fields
    DataFields = SRP_Rotate_Array(DataNames:@FM:DataRow)
    
    // Write the record
    Ans = SQL_Write(Connection, TableName, MvKeys, DataFields)

Until DataRowPos GE LenDataRows OR Ans NE ""
Repeat

// Delete any values beyond the number we just set
If Ans EQ "" AND iDataRow gt 0 then
    
    // Create the where clause expression from the array of keys
    KeyExpression = Keys
    Swap @VM with " = " in KeyExpression
    Swap @FM with " AND " in KeyExpression
    KeyExpression := " AND MV_NO >= ":(iDataRow + 1)

    // Run the script
    Script = "Delete From ":TableName:" where ":KeyExpression
    RecordSetResult = SRP_Com(Connection, "CALL", "Execute", Script)
    If RecordSetResult NE 0 then
        SRP_Com(RecordSetResult, "RELEASE")
    end else
        Ans = "Error deleting from ":TableName:" where ":KeyExpression:@TM:@TM:"Script = ":Quote(Script):@TM:@TM:SRP_Com(Connection, "ERROR")
    end
    
end

Return Ans
