0

I need your help.

I'd like to write a function that would detect and determine the operator (LIKE/=) to use in an SQL string

Example:

var input_string = "SELECT * from table WHERE [FIRSTNAME]"

var input_text = document.GetElementbyId('firstname').value

if 1 of the 4 possible combinations are met from the given input_text then the operator value will be "LIKE", else it is an equal sign (=)

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%

Example:

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%'

else

SELECT * FROM TABLE WHERE [FIRSTNAME] = 'firstname'
Yuriy Galanter
  • 36,794
  • 12
  • 65
  • 122
John Smith
  • 1,559
  • 10
  • 34
  • 51

3 Answers3

0

Since using like depends on having the % you should simply check for the % character within your string using indexOf method.

Example:

function useLike(input_text)
{
  return input_text.indexOf('%')>-1;
}
Menelaos
  • 22,383
  • 14
  • 83
  • 147
0

You seem to want

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+"'";

However, as @RocketHazmat mentioned in the comments, you could just use LIKE always and it would work like = when there are no percent signs in the string.

Bergi
  • 572,313
  • 128
  • 898
  • 1,281
  • Using `=` is faster if you don't have wildcards. http://stackoverflow.com/questions/559506/mysql-using-like-vs-for-exact-string-match – Menelaos Sep 30 '13 at 20:13
  • Is it? To cite paxdiablo, "*In a decent DBMS (e.g., DB2 :-), the DB engine would recognize that there were no wildcard characters in the string and implicitly turn it into an `=` version*". And that was 2009. – Bergi Sep 30 '13 at 20:21
  • ... you know that phrase about assumptions :)... but anyway, speed difference even if DB does not check will be negligible. – Menelaos Sep 30 '13 at 20:22
0

You should just be able to use LIKE regardless.

SELECT * FROM table WHERE firstname LIKE 'John'

Is a valid query.

gen_Eric
  • 214,658
  • 40
  • 293
  • 332