Sentencia de selección de SQL

in a string array i have a variable amount of values. how will an sql statement look if i want to select all the records that are equal with the array variables.

it will look something this:

SELECT * FROM users WHERE username='"+ variable amount of elements in the String array like: Steven, Mike, John ..... +"'"

preguntado el 08 de enero de 11 a las 17:01

4 Respuestas

You might be looking for the IN( ) operator.

SELECT * FROM users WHERE username IN ('chris', 'bob', 'bill');

Respondido el 08 de enero de 11 a las 20:01

This? (obviously the "OR username='xxx' is repeated for as many items as you require)

SELECT * FROM users WHERE username='item1' OR username='item2' OR username='item3'

Respondido el 08 de enero de 11 a las 20:01

Every one above me is corrrect! There are multiple ways of doing this! A simple google search for 'mysql statement variables' yield tons of help full results including:

Just treat your array like a standard varible with [a number] on the end!

Two tips come from this:

Google / Search your problem first 9 times out of 10 someone else has had the same problem and found a working solution!

And be prepared to look at the answers on here with in 5 mins. This forums probably the quickest you'll ever see. The only thing that slows the community down is typing ! :P

Espero que ayude,


Respondido el 08 de enero de 11 a las 20:01

Another approach, although less efficient, can be used if parsing the string apart is problematic...

DECLARE @listOfNames VARCHAR(2000)

SELECT * FROM users WHERE charindex(","+userName+",",","+@listOfNames+",") > 0

This approach is slower than either of the other answers, but can save you from using dynamic SQL to build a SQL query based on the list of names passed in...

Respondido el 08 de enero de 11 a las 21:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.