Re-write SQL main

adjusted affected scripts