Hvis skill2
feltet er af typen Char\VarChar2\NChar
osv. skal vi opregne registrerer f.eks.
using (MySqlConnection cons = new MySqlConnection(MyConString)) {
cons.Open();
string query =
@"SELECT DISTINCT(skill2) AS skills
FROM agentdetails";
using (new MySqlCommand(query, cons)) {
using (var reader = command.ExecuteReader()) {
// collection to store skills
HashSet<string> hs = new HashSet<string>();
// Enumerate all records
while (reader.Read())
hs.Add(Convert.ToString(reader[0])); // and add them into a collection
// join collection into string
string skills = string.Join(",", hs.Select(item => $"'{item}'"));
//TODO: put relevant code here (e.g. return skills)
}
}
}
Rediger: $"..."
er en strenginterpolation , hvis du bruger en ældre version af c# / .Net, som ikke understøtter det (se kommentar nedenfor) kan du prøve string.Format
i stedet:
string skills = string.Join(",", hs.Select(item => string.Format("'{0}'", item)));
Rediger 2: Undlad at hardkode forespørgsler, men parametriser dem; desværre, du kan ikke overføre en samling til IN
som en enkelt parameter:
using (MySqlConnection con2 = new MySqlConnection(MyConString)) {
con2.Open();
string hcount =
string.Format( @"SELECT SUM(headCount) AS THC,
date AS date1
FROM setshrinkage
WHERE skill IN ({0})
AND date BETWEEN @today1 AND @today2
GROUP BY date", skill);
using(MySqlCommand cmd2 = new MySqlCommand(hcount, con2)) {
//TODO: provide actual RDBMS type - Add(...) instead of AddWithValue(...)
cmd2.Parameters.AddWithValue("@today1", today1);
cmd2.Parameters.AddWithValue("@today2", today2);
using (MySqlDataReader myread2 = cmd2.ExecuteReader()) {
while (myread2.Read()) {
//TODO: provide relevant code here
}
}
}
}