Using IN
with a Parameterised Query isn't Hard
Posting this here in relation to another question that was marked as a duplicate of this one.
This isn't as difficult as you think, the adCmdText
query just needs to the placeholders in the query to match the number of parameters and their ordinal position and it will work with any number of parameters you pass into an IN
statement.
Here is a quick example using the AdventureWorks example database in SQL Server. We use an Array
to store the id of each Person.Contact
record we wish to filter out using IN
than build the parameters dynamically based on that array before executing the ADODB.Command
.
Note: The source of the array is not important it could be a string list which is Split()
into an Array
or just an Array()
call (like the one used in this example).
<%
Option explicit
%>
<!-- #include virtual = "/config/data.asp" -->
<%
Dim cmd, rs, sql, data, rows, row
'Our example parameters as an Array for the IN statement.
Dim ids: ids = Array(2, 5, 10)
Dim id
sql = ""
sql = sql & "SELECT [FirstName], [LastName] " & vbCrLf
sql = sql & "FROM Person.Contact " & vbCrLf
sql = sql & "WHERE [ContactId] IN (?, ?, ?) " & vbCrLf
sql = sql & "ORDER BY [LastName], [FirstName]" & vbCrLf
Set cmd = Server.CreateObject("ADODB.Command")
With cmd
.ActiveConnection = conn_string
.CommandType = adCmdText
.CommandText = SQL
'Loop through the Array and append the required parameters.
For Each id in ids
Call .Parameters.Append(.CreateParameter("@id" & id, adInteger, adParamInput, 4))
.Parameters("@id" & id).Value = id
Next
Set rs = .Execute()
'Output the Recordset to a 2-Dimensional Array
If Not rs.EOF Then data = rs.GetRows()
Call rs.Close()
End With
Set cmd = Nothing
If IsArray(data) Then
rows = UBound(data, 2)
For row = 0 To rows
Call Response.Write("<p>" & data(0, row) & " " & data(1, row) & "</p>" & vbCrLf)
Next
End If
%>
Output:
<p>Catherine Abel</p>
<p>Pilar Ackerman</p>
<p>Ronald Adina</p>
Worth noting this example shows the explicit way of writing the parameter code for an elegant approach to the problem see the second solution in @Bond's answer.