在使用SQLParameter時,如果需要傳遞一個數組作為參數,可以使用以下方法:
例如:
int[] ids = new int[] {1, 2, 3, 4};
string idString = string.Join(",", ids);
string query = "SELECT * FROM table WHERE id IN (@Ids)";
SqlCommand cmd = new SqlCommand(query, connection);
cmd.Parameters.AddWithValue("@Ids", idString);
例如:
int[] ids = new int[] {1, 2, 3, 4};
string query = "SELECT * FROM table WHERE id IN (" + string.Join(",", ids.Select((s, i) => "@Id" + i)) + ")";
SqlCommand cmd = new SqlCommand(query, connection);
for (int i = 0; i < ids.Length; i++)
{
cmd.Parameters.AddWithValue("@Id" + i, ids[i]);
}
這樣就可以將數組作為參數傳遞給SQL查詢語句。