Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
I work in windows form application c# vs2015 integrated to sql server 2012
I face problem
i need to select more specific number in same time but i dont know
what query i write or what i do in c#
current i using select * from table where userID=@UserID
this is select only number
but if i need to select more specific number
suppose i have numbers from 1001 to 1020
i need to select 1005,1009,1012,1017
How to get result for more records from SQL query or c# in same time
any way i can accept

What I have tried:

can i more select specific number from sql query in c#
Posted
Updated 30-Mar-17 5:38am

Have you tried the 'IN' SQL operator ?

SQL
select * from table
where userID=@UserID
and number in (1005, 1009, 1012, 1017)
 
Share this answer
 
In addition to IN, if it is a range you want to select then

WHERE userID >= 1001 AND userID <=1020
 
Share this answer
 
Comments
ahmed_sa 30-Mar-17 6:55am    
THANK YOU FOR REPLY
if i need it dynamically in textbox
my secnario as following
textbox have values 1002,1991,2007,3006
so that how to select these values
Quote:
textbox have values 1002,1991,2007,3006
so that how to select these values

You'll need to split the text, convert each value to an integer, and build up a parameterized SQL command using the IN operator:
C#
string text = YourTextBox.Text;
string[] parts = text.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

string[] parameterNames = new string[parts.Length];
SqlParameter[] parameters = new SqlParameter[parts.Length];

for (int index = 0; index < parts.Length; index++)
{
    int value;
    if (!int.TryParse(parts[index], out value))
    {
        // TODO: Display an error to the user
        return;
    }
    
    string name = "@p" + index;
    parametersNames[index] = name;
    parameters[index] = new SqlParameter(name, SqlDbType.Int) { Value = value };
}

string sql = string.Format("SELECT * FROM table WHERE userID IN ({0})", string.Join(", ", parameterNames));

using (var connection = new SqlConnection("..."))
using (var command = new SqlCommand(sql, connection))
{
    command.Parameters.AddRange(parameters);
    ...
}
 
Share this answer
 
Comments
F-ES Sitecore 30-Mar-17 12:24pm    
That won't work if the number of items exceeds 2100.
Richard Deeming 30-Mar-17 12:29pm    
True, but I couldn't be bothered to write the code to split the numbers into groups and recombine the results, just to support a case that the OP didn't request. :)

I doubt anyone would type in a list of 2100 numbers in a single textbox anyway.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900