0

I'm trying to create a search button that can filter through multiple table columns within a table, I have three seperate codes that can search a data on a particular table column (LastName, FirstName and DriverID):

SqlConnection Con = new SqlConnection();
Con.ConnectionString = "Data Source=PC-PC\\MIKO;
                        Initial Catalog=Caproj;
                        Integrated Security=True;";
Con.Open();
string qry = "select LastName from [Driver Table] where LastName=@id";
SqlCommand cmd = new SqlCommand(qry, Con);
cmd.Parameters.AddWithValue("@id", slastname.Text);
cmd.ExecuteNonQuery();
SqlDataAdapter da2 = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da2.Fill(dt);
if (dt.Rows.Count > 0)
 {
  MessageBox.Show("Valid Input");
 }
else
{
 MessageBox.Show("Invalid Input");
}

Is there a way where I can search them all at the same time without the need for making a separate filter for each? Something along the lines of this:

SELECT LastName, FirstName, DriverID 
FROM [Driver Table] 
WHERE LastName=@id 
  AND FirstName=@id 
  AND DriverID=@id

2 Answers 2

1

I am not sure if this what you need. But this query will return a 1 value when the id is existing from the 3 columns.

SELECT  
    CASE WHEN EXISTS (SELECT * FROM [Driver Table] WHERE LastName = @id) 
            THEN 1 
         WHEN EXISTS (SELECT * FROM [Driver Table] WHERE FirstName = @id) 
            THEN 1 
         WHEN EXISTS (SELECT * FROM [Driver Table] WHERE DriverID = @id) 
            THEN 1 
         ELSE 0 
    END
Sign up to request clarification or add additional context in comments.

2 Comments

Do I just remove the "1", If I only want it to select the statement without returning a 1 value?
If that's the case just replace the AND to an OR on your query.
0

If I understand correctly, don't you just want or:

SELECT LastName, FirstName, DriverID 
FROM [Driver Table] 
WHERE LastName = @id OR
      FirstName = @id OR
      DriverID = @id;

Or, more simply:

SELECT LastName, FirstName, DriverID 
FROM [Driver Table] 
WHERE @id IN (LastName, FirstName, DriverID);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.