passing an Array as a Parameter to be used in a SQL Query using the "IN" Command

14.7k views Asked by At

Good Afternoon to All,

I have a question concerning on SQL Queries. is it possible to use an array as a parameter to a query using the "IN" command?

for example,

int x = {2,3,4,5}

UPDATE 'table_name' set 'field' = data WHERE field_ID IN (x)

the reason I am asking this is to avoid an iterative SQL Statement when I have to update data in a database. I also thought of using a for each statement in for the UPDATE Query but I don't know if it will affect the performance of the query if it will slow down the system if ever 100+ records are updated.

I am using VB.Net btw. My Database is MySQL Workbench.

3

There are 3 answers

0
Law On BEST ANSWER

I have gotten the answer. I just simply need to convert each elements to a String then concatenate it with a "," for each element. so the parameter that i will pass will be a string.

ANSWER: int x = {2,3,4,5} will become string x = "2,3,4,5"

My Query string will become "UPDATE tablename SET field=value WHERE ID IN("&x&")"

Thank you to all who helped.

1
Rex On

i am not familiar with mySQL, but when dealing with MSSQL, I normally have a split function in DB so that I can use it to split concatenated integer values as a table, at VB side, something like:

        Dim myIds = {1, 2, 3, 4}
        Dim sql = <sql>                          
                    SELECT m.* FROM dbo.tblMyData m
                    INNER JOIN dbo.fncSplitIntegerValues(@Ids, ',') t ON t.id = m.Id
                  </sql>.Value

        Using con As New SqlConnection("My connection string..."),
            cmd As New SqlCommand(sql, con)

            cmd.Parameters.Add("@Ids", SqlDbType.VarChar).Value =
                myIds.Select(Function(m) m.ToString).Aggregate(Function(m, n) m & "," & n)

            con.Open()

            Dim rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
            While rdr.Read()
                Console.WriteLine(rdr.GetValue(0))
                ' do something else...
            End While

        End Using

dbo.fncSplitIntegerValues is a db function to split concatenated integer varchar into integer Id with given separator.

it's important not to use plain sql, instead, use sql parameters.

Note: above sample is not tested...

0
the_lotus On

If you have the query in a variable (not a stored procedure) and you don't have a huge amount of ids, you could built your own IN. I haven't tested the speed of this approach.

This code won't compile, it's just to give you an idea.

query = "SELECT * FROM table WHERE col IN ("

For t = 0 TO x.Length-1
    If t > 0 Then query &= ","

    query &= "@var" & t
Next

query &= ")"

...

For t = 0 TO x.Length-1
    cmd.Parameters.Add("@var" & t, SqlDbType.Int).Value = x(t)
Next