首页 > 解决方案 > Update table using only variables

问题描述

I have a table EmpTable like so: enter image description here

If I want to update the salary of John I can do it like so:

static void UpdateSal(Args _args)
{
    EmpTable EmpTable;
    real sal=110000;
    int RowId = 1;

    ttsBegin;
    select forUpdate EmpTable where EmpTable.Id==RowId;
    EmpTable.Salary=sal;
    EmpTable.update();
    ttsCommit;


}

I want help in implementing the above code with using only variables:

static void UpdateSal_WithStrValues(Args _args)
{

    str table = 'EmpTable'
    str field = 'Salary'
    int RowId = 1;
    real sal=110000;

    .....??
    .....??

}

Update:

This code works:

static void Job1(Args _args)
{
    SysDictTable dictTable = new SysDictTable(tablename2id('EmpTable'));
    Common common = dictTable.makeRecord();

    ttsbegin;
    while select forupdate common
        where common.(fieldName2id(tableName2Id("EmpTable"),'Id')) == 1
    {
        common.(fieldName2id(tableName2Id("EmpTable"),'Salary')) = 110100;
        common.update();
    }
    ttscommit;

}

But this code doesn't:

static void Job1(Args _args)
{

    str table = 'EmpTable';
    str fieldToUpdate= 'Salary';
    str fieldToSelect= 'Id';
    int RowId = 1;
    real sal=34536;

    SysDictTable dictTable = new SysDictTable(tablename2id(table));
    Common common = dictTable.makeRecord();


    ttsbegin;
    while select forupdate common
        where common.(fieldName2id(tableName2Id(table),fieldToSelect)) == RowId
    {
        common.(fieldName2id(tableName2Id(table),fieldToUpdate)) = sal;
        common.update();
    }
    ttscommit;

}

标签: axaptax++dynamics-ax-2012dynamics-ax-2012-r3

解决方案


将字符串绑定到固定长度解决了这个问题:

下面的代码现在可以工作:

static void Job1(Args _args)
{
    
    str 50 table = 'EmpTable';
    str 50 fieldToUpdate= 'Salary';
    str 50 fieldToSelect= 'Id';
    int RowId = 1;
    real sal=12213;
    
    SysDictTable dictTable = new SysDictTable(tablename2id(table));
    Common common = dictTable.makeRecord();
 
    
    ttsbegin;
    while select forupdate common
        where common.(fieldName2id(tableName2Id(table),fieldToSelect)) == RowId
    {
        common.(fieldName2id(tableName2Id(table),fieldToUpdate)) = sal;
        common.update();
    }
    ttscommit;

}

Martin Drab 提供的更好的解决方案:

static void Job1(Args _args)
{

    TableName table = 'EmpTable';
    FieldName fieldToUpdate= 'Salary';
    FieldName fieldToSelect= 'Id';
    int rowId = 1;
    real sal = 6546456;
    
    SysDictTable dt = SysDictTable::newName(table);
    Common common = dt.makeRecord();
    
    ttsbegin;
    while select forUpdate common
        where common.(dt.fieldName2Id(fieldToSelect)) == rowId;
    {
        common.(dt.fieldName2Id(fieldToUpdate)) = sal;
    
        if (!common.validateWrite())
        {
            throw error("Nope");
        }
        common.update();
    }
    
    ttscommit;
}

推荐阅读