Check unique key for multiple fields

 

MX Kollection provides a trigger as a server behavior that allows checking if the value in a transaction field already exists in the table, and stop the insert operation if true. This is useful when trying to prevent duplicate records - e.g. when registering user accounts. But in order to check multiple fields you have to build your own custom trigger. In the example below which uses the Discussion Board tutorial structure (both database and files), a custom trigger is built to prevent posting duplicate messages - which have the same subject and content.

The trigger retrieves the values of the subject and content fields from the transaction and uses them to build a select query. If the query yields any results, then the message is a duplicate and the transaction is stopped. The trigger uses only the methods explained for the Execute sql queries and Use transaction fields sections, and the basic structure is as follows:

 

//first retrieve the transaction fields' values and store them in local variables, for convenience
subject = tNG.getColumnValue("subject_field")
content = tNG.getColumnValue("content_field");

 

//next use the two values to build the query
query = "SELECT * FROM [message_table] WHERE subject_field = ".KT_escapeForSql(subject ,"STRING_TYPE")." AND content_field = ".KT_escapeForSql(content ,"STRING_TYPE")

 

//run the query and retrieve the result into a variable
result = tNG.connection.execute(query)

 

//check if the resulted recordset contains any records; if not, return NULL
if( result.recordCount() = 0)
return NULL
//otherwise, create a new error object and return it
check_failed = new tNG_error("Error message",array(), array())
return check_failed

 

The structure above, adapted to your particular scripting language and scenario allows building the custom trigger to check for unique entries. From the trigger properties page, you must set it to the BEFORE type, so that it is executed before the actual insert, and will block it if it fails.

Next you will see an example of a multiple field unique check created for the Discussion Board tutorial scenario, for all server models: