简体   繁体   中英

Select Count query in DB2 with Array

I am trying to Count all records in my DB2 database with a query where is uses the contents of an Array to search the Table.

           string[] strNumbers = txtNumbers.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

               string strSearch = "";
                   strSearch = "SELECT COUNT(*) FROM TABLENAME WHERE NUMBER = '" + strNumbers + "' AND COMMENT = '" + strMessage + "'";

                DB2Command cmdSearchTable = new DB2Command(strSearch, db2Connection);

                int nodeCount = 0;
                nodeCount = int.Parse(cmdSearchTable.ExecuteScalar().ToString());

if (nodeCount == 0) {
 Not Found          
 } else
  { Found
   }

This code throws up an exception ({"The value of a host variable in the EXECUTE or OPEN statement is out of range for its corresponding use."})

However if I use strNumbers.Length it doesn't throw up an error but the nodeCount it still 0.

Do I need to loop it or is it something else? The query and database connection is fine as I am able to Select,Insert into the database from the same program.

Thanks

EDIT - I have managed to solve this (See accepted answer) but now have a another problem. Lets say '1234567' is in the database once it will return 1 which is fine. If the input it '5551234' which isn't in the database it returns 0 which is also fine. However the problem lies with if the input is '1234567,5551234' the Count will return 1 as 1234567 is in the database, even though 5551234 isn't.

Is there a way of outputting 1 for 1234567 and then 0 for 5551234?

Try changing

WHERE NUMBER = '" + strNumbers + "' AND

with

WHERE NUMBER IN (" + strNumbers + ") AND

Make sure that strNumbers is comma separated. Something like this '12345', 12346', '12347' or 12345,12346,12347 depending on the datatype of the field NUMBERS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM