A
A
Alexey Lebedev2017-04-26 10:58:47
SQL
Alexey Lebedev, 2017-04-26 10:58:47

How to correctly pass an array as a parameter to a SQL query?

We have such a request.

SQLname = "SELECT name FROM dbo.table WHERE id IN("+String.Join(",", items.ToArray())+");";
                using (var comm = new SqlCommand(SQLname, conn, null))
                {

                    using (var reader = comm.ExecuteReader())
                    {
                        while (reader.Read())
                        {
   
                        }                          
                    }
                }

What is the best way to pass a list for IN?
Maybe somehow you can parameterize or do it more correctly, the main problem is that the values ​​\u200b\u200bcan be from 1 to 1000.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrew, 2017-04-26
@Dronablo

Not the newest article, but nevertheless: Tests of methods for passing list variables to storage... .

V
vvovas, 2017-04-26
@vvovas

I think through xml the parameter will be the easiest way. In procedure you will make join.
something like:

create procedure p(
  @ids xml
)
begin
  select name 
  from 
    dbo.table 
    inner join @ids.nodes('/items/item') root(items) 
      on id = items.value('(text())[1]', 'int')
end

in the example xml will look like
<items>
  <item>1</item>
  ...
  <item>1000</item>
</items>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question