So I am currently working on a project where I am looking to retrieve all data from a table matching a modifyable list on the screen. Here is a sample of the code that I am using to make the call
Public Sub GetAnimals(ByReg selectedTypes As String)
Dim strSql As String
Dim pselectedTypes As SqlClient.SqlParameter = New SqlClient.SqlParameter("@pselectedTypes", selectedTypes)
Dim strDBConnection As String = DBConnection.GetConnection.ConnectionString
Dim rs As DataSet = new DataSet
strSql = "SELECT * FROM PetInformation WHERE AnimalType IN (@pselectedTypes)"
Using sqlConn As SqlClient.SqlConnection = New SqlClient.SqlConnection(strDBConnection)
sqlConn.Open()
Using sqlcmd As SqlClient.SqlCommand = New SqlClient.SqlCommand
With sqlcmd
.Connection = sqlConn
.CommandTimeout = DBConnection.DLLTimeout
.CommandType = CommandType.Text
.CommandText = strSql
.Parameters.Add(pselectedTypes)
Using sqlda As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(sqlcmd)
sqlda.Fill(rs)
End Using
End with
End Using
End Using
' Data Calculations
End Sub
This then makes the SQL query look something like this. For this example I'm using my list of animals as just cats and dogs.
exec sp_executesql N'SELECT * FROM PetInformation WHERE AnimalType IN (@pselectedTypes)',N'@pselectedTypes nvarchar(22),@pselectedTypes='''cat'',''dog'''
So everything looks all fine and dandy but when I go to run it and execute it I don't get any results back. If I change the sql to look like either one of these I get data back, but since this SQL is generated that's not really an option w/o switching away from parameterized sql, which I don't want to do.
exec sp_executesql N'SELECT * FROM PetInformation WHERE AnimalType IN (''cat'',''dog'')',N'@pselectedTypes nvarchar(22),@pselectedTypes='''cat'',''dog'''
or
SELECT * FROM PetInformation WHERE AnimalType IN ('cat','dog')
Any suggestions or ideas?