Script Help !!

vidishaagarwal5
Tera Expert

Hi Team,

I have the below scenario to be implemented help here please.

When a record from the Knowledge Base (kb_knowledge) table is deleted, you want to delete all its attachments to save space.

4 ACCEPTED SOLUTIONS

Ravi Gaurav
Giga Sage

Hi @vidishaagarwal5 

 

The Below Simple code will help you !!

 

// Table: kb_knowledge
// When: before delete
(function executeRule(current, previous) {
var attachmentGR = new GlideRecord('sys_attachment');
attachmentGR.addQuery('table_name', 'kb_knowledge');
attachmentGR.addQuery('table_sys_id', current.sys_id);
attachmentGR.query();

while (attachmentGR.next()) {
attachmentGR.deleteRecord();
}
})(current, previous);

View solution in original post

Raghav Sharma24
Giga Patron

kb_knowledge is the table for knowledge articles not knowledge base.

Try this script in After Delete Business rule on kb_knowledge table:

 

    var att = new GlideRecord('sys_attachment');
    att.addEncodedQuery('table_sys_id=' + current.sys_id);
    att.query();
    att.deleteMultiple();


Please mark the answer correct/helpful accordingly.

 

View solution in original post

Tejas Adhalrao
Mega Sage

Hi @vidishaagarwal5 ,

1) on  you table you can create the after business rule (delete)

TejasSN_LogicX_0-1760514865548.png

 and paste this script in your business rule

(function executeRule(current, previous /*null when async*/) {

    //thiss  Find all attachments linked to this Knowledge record
    var attachmentGR = new GlideRecord('sys_attachment');
    attachmentGR.addQuery('table_sys_id', current.sys_id);
    attachmentGR.addQuery('table_name', 'kb_knowledge');
    attachmentGR.query();

    //now  Delete each attachment
    while (attachmentGR.next()) {
        attachmentGR.deleteRecord();
    }

})(current, previous);

 

If my response/article helped you, please mark it as the correct answer and close the thread — this helps other readers in the community.

Regards,

Tejas 
🚀 ServiceNow Developer | 🏆 HackaNow Finalist | 💡 Community Contributor
📧 Email: tejas.adhalrao11@gmail.com
🔗 LinkedIn: linkedin.com/in/tejas1018

View solution in original post

miftikhar20
Kilo Patron

@vidishaagarwal5,Once you delete an article record, no attachment will appear in the sys_attachment table, so they are removed automatically from there but might still remain part of the system. Follow this thread to remove them permanently.

https://www.servicenow.com/community/developer-forum/finding-and-deleting-orphaned-attachments/m-p/2... 

View solution in original post

5 REPLIES 5

miftikhar20
Kilo Patron

@vidishaagarwal5,Once you delete an article record, no attachment will appear in the sys_attachment table, so they are removed automatically from there but might still remain part of the system. Follow this thread to remove them permanently.

https://www.servicenow.com/community/developer-forum/finding-and-deleting-orphaned-attachments/m-p/2...