I have webservice which is passed an array of ints. I'd like to do the select statement as follows but keep getting errors. Do I need to change the array to a string?
[WebMethod]
public MiniEvent[] getAdminEvents(int buildingID, DateTime startDate)
{
command.CommandText = @"SELECT id,
startDateTime, endDateTime From
tb_bookings WHERE buildingID IN
(@buildingIDs) AND startDateTime <=
@fromDate";
SqlParameter buildID = new SqlParameter("@buildingIDs", buildingIDs);
}
A superfast XML Method which requires no unsafe code or user defined functions :
You can use a stored procedure and pass the comma separated list of Building IDs :
All credit goes to Guru Brad Schulz's Blog
I use that approach and works for me.
My variable act = my list of ID's at string.
Perhaps I'm being over detailed, but this method accepts a single int, not an array of ints. If you expect to pass in an array, you will need to update your method definition to have an int array. Once you get that array, you will need to convert the array to a string if you plan to use it in a SQL query.
Here's a Linq solution I thought up. It'll automatically insert all items in the list as parameters @item0, @item1, @item2, @item3, etc.
You can't (unfortunately) do that. A Sql Parameter can only be a single value, so you'd have to do:
Which, of course, requires you to know how many building ids there are, or to dynamically construct the query.
As a workaround*, I've done the following:
which will replace the text of the statement with the numbers, ending up as something like:
NOTE: I am not generally for using unparameterized queries. IN THIS INSTANCE, however, given that we are dealing with an integer array, you could do such a thing and it would be more efficient. However, given that everyone seems to want to downgrade the answer because it doesn't meet their criteria of valid advice, I will submit another answer that performs horribly but would probably run in LINK2SQL.
Assuming, as your question states, that you have an array of ints, you can use the following code to return a string that would contain a comma delimited list that SQL would accept:
Then, I would recommend you skip trying to parameterize the command given that this is an array of ints and just use: