我有一个带有SQL语句的数组:
var sql=[ "select sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL ",
"select mes,sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL GROUP BY mes"
];
我需要在每个语句中放置一个where子句。 问题是当我有其他条款而不是WHERE我需要将WHERE子句放在所有其他子句之前。我试着这样做,但没有运气。
var clauses=['GROUP','HAVING'];
_.forEach(sql, function (sq, key) {
clauses.map(function (clause) {
if (sq.indexOf(clause) !== -1) {
debugger;
sql[key]=[sq.slice(0, sq.indexOf(clause)), ' where '+obj.where_str+' ', sq.slice(sq.indexOf(clause))].join('');
return false;
}else{
debugger;
sql[key]=sq+" where " + obj.where_str;
return false;
}
});
});
答案 0 :(得分:0)
我建议您使用RegExp解决问题。
使用以下RegExp,您可以找到Select是否具有GROUP或HAVING运算符。
var pattern = /(select.*)((?:GROUP|HAVING).*)/i;
然后你可以针对你的阵列测试这种模式:
var arr = ['select mes,sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL GROUP BY mes',
'select sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL ',
'select sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL HAVING sadsa'];
arr.forEach(function(select, index){
var n = pattern.exec(select); // execute the pattern agains the current Select
if(!n){ // if it not match any GROUP or HAVING,
arr[index] += arr[index] + ' your_WHERE '; // append your Where at the end
return;
} // if match, append yout Where in the middle
arr[index] = n[1] + ' your_WHERE ' + n[2];
});
结果将是:
0:"select mes,sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL your_WHERE GROUP BY mes"
1:"select sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL "
2:"select sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL your_WHERE HAVING sadsa"
希望它有所帮助。
答案 1 :(得分:0)
这只是我身边的尝试..请看看。
以下代码将在from ..
语句之后添加新的where子句。所以它永远是第一位的。
var str= "select sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL groupBy....";
var newStr = 'where something > 12'
var first_part = str.substr(0,str.indexOf('from')+5);
var second_part_tmp = str.substr(str.indexOf('from')+6);
var second_part = second_part_tmp.substr(0,second_part_tmp.indexOf(' '));
var third_part = second_part_tmp.substr(second_part_tmp.indexOf(' '));
if(second_part.indexOf(' ')!=0){
}
console.log(first_part,second_part, third_part);
console.log([first_part,second_part,newStr, third_part].join(' '))

答案 2 :(得分:0)
谢谢大家,但我简化了一些事情。
我只是替换:where
var sql=[
"select sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL :where",
"select mes,sum(custo) as TOTAL from PRS_CUSTOS_MATERIAL :where GROUP BY mes"
];
使用
_.forEach(sql, function (sq, key) {
sq=sq.replace(":where", ' where '+obj.where_str);
sql[key]=sq
});