user17510 user17510 - 1 year ago 132
SQL Question

sqlParameter conversion

I'm trying to call the SQL statement below but get the following error:

System.Data.SqlClient.SqlException: Conversion failed when converting
the varchar value '+@buildingIDs+' to data type int.

@"SELECT id, startDateTime, endDateTime
FROM tb_bookings
WHERE buildingID IN ('+@buildingIDs+')
AND startDateTime <= @fromDate";

is an
type column in the db. Will I need to pass the IDs as an array of ints?

Answer Source

Bravax's way is a bit dangerous. I'd go with the following so you don't get attacked with SQL Injections:

int[] buildingIDs = new int[] { 1, 2, 3 };

/***/ @"SELECT id, startDateTime, endDateTime From tb_bookings WHERE buildingID IN (" +
      string.Join(", ", buildingIDs.Select(id => id.ToString()).ToArray())
      + ") AND startDateTime <= @fromDate"; 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download