Can I create a custom table via a script?

Todd O
Tera Guru

Is it possible to create a SN custom table via a script? I would like to create many tables that are coming from a different database. I would like to write a script to read in that ddl and then translate that to whatever SN needs to create these tables. It will save me a lot of typing. Thank you in advance.

Todd

1 ACCEPTED SOLUTION

Here's an example of adding a new extended table and a column



// create a new table 'abc' by extending 'task' and add new string column 'myfield'


var table_name = 'abc', extends_table = 'task', fname = 'myfield';



var attrs = new Packages.java.util.HashMap();
var ca = new GlideColumnAttributes(fname);
ca.setType("string");
ca.setUsePrefix(false);
attrs.put(fname, ca);



var tc = new GlideTableCreator(table_name , table_name);
tc.setColumnAttributes(attrs);
if(typeof extends_table != 'undefined') tc.setExtends(extends_table);
tc.update();



You can run this in Background Script and go to System Definition > Tables or Tables & Columns to see the new table and column.


View solution in original post

20 REPLIES 20

drjohnchun
Tera Guru

If you look into the ImportSetUtil Script Include, you'll find the GlideTableCreator class and script for creating tables.



Hope this helps.



Please feel free to connect, follow, mark helpful / answer, like, endorse.


John Chun, PhD PMP see John's LinkedIn profile

visit snowaid


ServiceNow Advocate

Winner of November 2016 Members' Choice Award


Hi John,


I see the ImportSetUtil within the Script includes. I then see the GlideTableCreate class too. Where is this class defined so that I can see all of it's capabilities? I cannot find it in the script includes location, nor is there any documentation on this. Thanks again for the help.


Todd


I'm not aware of any formal documentation. I'd suggest trying to understand what the ImportSetUtil Script Include does rather than focusing on GlideTableCreator (it's internally defined, so we don't have access to all the details) - you can follow along the script and see that you can either create a table from an XML via the attr variable or set field attributes using script as in the copyFields() function. You can copy the entire script to Background Script, rename it, instantiate it, and give it a try in a dev instance, inspecting variables and XML as you go.


 


Below is other way to create table using script.



var tbl = new GlideRecord('sys_db_object');


tbl.name = <table name>;


tbl.label = <table display name>;


tbl.insert();