我將一長串employeeIds傳遞給employeeIdlist
,然後將它們分成一個List。使用這個列表,我將參數添加到我的查詢中。 我收到以下錯誤必須在Select命令中聲明標量變量
{「必須聲明標量變量\」 @僱員\「」}
public List<versionInfo> GetVersion(string employeeIdlist)
{
DbHelper helper = new DbHelper();
List<versionInfo> empVerInfo = new List<versionInfo>();
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand getVersion = new SqlCommand())
{
getVersion.Connection = conn;
getVersion.CommandText = @"SELECT EmployeeId,Version
FROM [dbo].[EmployeeVersion]
WHERE EmployeeId in (@EmployeeId)";
getVersion.CommandType = CommandType.Text;
List<int> empIds = employeeIdlist.Split(',').Select(int.Parse).ToList();
StringBuilder sb = new StringBuilder();
int i = 0;
foreach (var emp in empIds)
{
// IN clause
sb.Append("@EmployeeId" + i.ToString() + ",");
// parameter
getVersion.Parameters.AddWithValue("@EmployeeId" + i.ToString(), emp);
i++;
}
// getVersion.Parameters.AddWithValue("@EmployeeId", employeeIdlist);
SqlDataReader rdr = getVersion.ExecuteReader();
while (rdr.Read())
{
versionInfo vi = new versionInfo();
vi.employeeId = helper.GetDb<int>(rdr, "EmployeeId");
vi.version = helper.GetDb<decimal>(rdr, "Version");
empVerInfo.Add(vi);
}
rdr.Close();
}
conn.Close();
}
return empVerInfo;
}
您正在添加多個參數,將您的AddWithValue保留在循環中;使用String.Join連接列表並最終只添加一個參數 – techspider
我建議將sql移入存儲過程並聲明名爲'@ EmployeeId'的輸入參數,並且您有一個EmployeeId列表我還會創建一個類型並傳遞在列表中讓數據庫處理IN子句你是否熟悉在sql server中創建用戶類型..? – MethodMan