我需要你的帮助。
我想编写一个函数来检测和确定要在SQL字符串中使用的运算符(LIKE / =)
示例:
var input_string = "SELECT * from table WHERE [FIRSTNAME]"
var input_text = document.GetElementbyId('firstname').value
如果从给定的input_text满足4种可能组合中的1种,则运算符值将为“LIKE”,否则为等号(=)
1.) At the start of the string: %firstname
2.) somewhere in the string itself: first%name
3.) At the end of the string: firstname%
4.) at both ends of the string: %firstname%
示例:
var output_string = input_string + analyze(input_text) '+input_text+'
var output_string examples:
SELECT * FROM TABLE WHERE [FIRSTNAME] LIKE '%firstname%'
SELECT * FROM TABLE WHERE [FIRSTNAME] LIKE '%first%name'
SELECT * FROM TABLE WHERE [FIRSTNAME] LIKE 'firstname%'
SELECT * FROM TABLE WHERE [FIRSTNAME] LIKE '%firstname%'
否则
SELECT * FROM TABLE WHERE [FIRSTNAME] = 'firstname'
答案 0 :(得分:0)
由于使用like取决于拥有%
,您应该使用indexOf方法检查字符串中的%
字符。
示例:
function useLike(input_text)
{
return input_text.indexOf('%')>-1;
}
答案 1 :(得分:0)
你似乎想要
function analyze(compare) {
if (compare.indexOf("%") > -1)
return "LIKE";
else
return "=";
// or shorter with a regex and conditional operator:
return /%/.test(compare) ? "LIKE" : "=";
}
var output_string = input_string+" "+analyze(input_text)+"'"+input_text+"'";
但是,正如@RocketHazmat在评论中提到的那样,您可以始终使用LIKE
,当字符串中没有百分号时,它会像=
一样工作。
答案 2 :(得分:0)
您应该只能使用LIKE
。
SELECT * FROM table WHERE firstname LIKE 'John'
是有效查询。