Creating Tables Via Script

Sometimes there’s a need to create a table via script.

In this post I’ll share short code on how you can:

  1. Create a copy of an existing table
  2. Create an extension of an existing table

Both use the out of the box TableDescriptor script include. ServiceNow uses the same code when creating table rotations.

Creating a copy of an existing table

//Pass in the table you want to copy
copyTable("incident");
function copyTable(tableName) {
var gr = new GlideRecord(tableName);
gr.initialize();
//Gets the descriptor for the table which contains all the details for the table
var td = GlideTableDescriptor.get(tableName);
var displayName = td.getDisplayName();
var tLabel = gr.getLabel();
//change this prefix to whatever you want it to be. Note that if you don't name it with u_, you won't be able to delete it
var tName = "cp_" + tableName;
var creator = new TableDescriptor(tName, tLabel);
//checks if this table is an extension
var db = new GlideRecord("sys_db_object");
db.addEncodedQuery("super_classISNOTEMPTY^name=" + tableName);
db.setLimit(1);
db.query();
if (db.next()) {
creator.setExtends(db.super_class + '');
}
creator.setFields(gr);
creator.copyAttributes(td);
//copies the security to the new table
creator.setRoles(td);
//Until this point, the table isn't actually created
creator.create();
//Finally we copy the indexes from the original table to the new table
creator.copyIndexes(tableName, tName);
}

Creating an extension of an existing table (this is a lot easier)

createExtension("u_my_new_app", "My new application", "task");
function createExtension(tableName, tableLabel, extends) {
var creator = new TableDescriptor(tableName, tableLabel);
creator.setExtends(extends);
creator.create();
}

2 Comments

  1. nice script.. but I found that it wont capture the changes in updateset. So I ran a background script to update comments for the columns so that it gets captured in updateset, and I changed label of the table which got the table into the updateset.

    background script used
    var tName =”;
    commentColumns(tName);
    function commentColumns(tName) {
    var gr = new GlideRecord(‘sys_dictionary’);
    gr.addEncodedQuery(‘name=’+tName);
    gr.query();
    while(gr.next()) {
    gr.comments = tName + ‘comment’ ;
    gr.update();
    }
    }

    Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s