Service Board > Max for Developers > Max Groovy APIs > SMQL > Updating Records With SMQL
Updating Records With SMQL
To update existing records, you must first query them in the database, after which you can modify fields. After you complete your changes, you call Database.update.
def records = Database.query("SELECT io_uuid, io_name FROM
io_basic_object_for_test where io_uuid = :io_uuid",
[io_uuid:recordUUID]);
def record = records.get(0);
record.io_name = 'another name'
Database.update(record)
Records can be updated in batches also.
def records = Database.query("SELECT io_uuid, io_name FROM io_basic_object_for_test");
records[0].io_name = "a new name";
records[1].io_name = "a new name";
Database.update(records);
By default, validation is not executed at the Groovy level, but is executed before the record is inserted into the database.
def records = Database.query("SELECT io_uuid, io_name FROM
io_basic_object_for_test where io_uuid = :io_uuid",
[io_uuid:recordUUID]);
def record = records.get(0);
record.io_name = null
Database.update(record) //this will run OK but an exception will be thrown before the record is updated in the database
For immediate validation, you can display an error code or throw an exception. For example, to throw a DmlException exception when validation errors occur:
def records = Database.query("SELECT io_uuid, io_name FROM
io_basic_object_for_test where io_uuid = :io_uuid",
[io_uuid:recordUUID]);
def record = records.get(0);
record.io_name = null
try {
Database.update(record)
} catch(DmlException e) {
e.getNumDml() // Number of errors
e.getDmlMessage(0); //Message for the Nth error
}
To get a result for each saved record instead of an exception:
def records = Database.query("SELECT io_uuid, io_name FROM
io_basic_object_for_test where io_uuid = :io_uuid",
[io_uuid:recordUUID]);
def record = records.get(0);
record.io_name = null
def result = Database.update(record, Database.ValidationMode.ReturnErrorOnValidationError)
result.isSuccess() //false if validation failed
result.getErrors().size() //number of errors in the insert
result.getErrors()[0].getMessage() //Message for the Nth error
To append value to fields with large Arrays or Texts:
import com.servicemax.core.Database

def record = Database.querySingleResult("Select * from io_showcase where io_uuid = '42f64596-c42f-4ba2-8138-cc40188d2a88'")

def tmp = [["es", "perro"]]

record.appendToField("io_showcase_text_localized", tmp)

record.update()
For more information:
Was this helpful?