I was looking for a script which do the above. I couldn't find any. So I wrote a one. The following function takes a sql query string such as
"SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons INNER JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName SELECT AVG(OrderPrice) AS OrderAverage FROM Orders" and returns a string array containing LastName,FirstName,OrderNo.
"SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons INNER JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName SELECT AVG(OrderPrice) AS OrderAverage FROM Orders" and returns a string array containing LastName,FirstName,OrderNo.
function brakeColumns(query) {
var columnList = new Array();
var patten1 = /^[\w\$][\w]*/i;
var patten2 = /^[\w\$][\w]*\.[\w\$][\w]*$/i;
var numEnd = query.search(/\sfrom\s/i);
var elems = (query.substring(6, numEnd)).split(",");
for (var i = 0; i < elems.length; i++) {
var elem = elems[i].toString();
elem = trim(elem);
var stPoint = "";
var wanted = "";
if (elem.search(/\sas\s/i) != -1) {
stPoint = elem.search(/\sas\s/i);
wanted = elem.substring(stPoint + 4);
wanted = trim(wanted);
if (patten1.test(wanted)) {
columnList.push(wanted);
}
} else if (patten2.test(elem)) { //check for tablename.column name pattern
stPoint = elem.search(/\./);
wanted = elem.substring(stPoint + 1);
wanted = trim(wanted);
if (patten1.test(wanted)) {
columnList.push(wanted);
}
} else { //check for straight column name like username,passsword etc
if (patten1.test(elem)) {
columnList.push(elem);
}
}
}
return(columnList);
}
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g, "");
}
Comments