-1

我正在尝试执行参数化的 SQLCommand,它应该返回 1 个值。相反,它返回一个空集,不抛出异常,程序继续运行。

这是查询:

SELECT SUM(s.cost) AS cost
FROM Spending s JOIN Date d ON s.dateID = d.dateID 
    JOIN [Service category] sc ON s.[service categoryID] = sc.[service categoryID]
WHERE sc.category1 = 'Phone' AND s.personID = @person
    AND d.month = @month AND d.year = @year

C#代码如下:

        SqlCommand commandSelect = new SqlCommand(query, conn);
        foreach (string[] p in pars)
        {
            commandSelect.Parameters.AddWithValue("@" + p[0], p[2]);
        }
        SqlDataReader res = commandSelect.ExecuteReader();

其中有 3 个参数传递,当我在调试器中检查 SQLcommand 时,它们被正确传递。@person 是一个字符串,另外两个是整数。

任何帮助,将不胜感激。

编辑:我可能还应该添加 pars 数组的结构:

pars[0][0] = "person"
pars[0][2] = "'IDString here'"
pars[1][0] = "month"
pars[1][2] = "2"
pars[2][0] = "year"
pars[2][2] = "2012"
4

2 回答 2

3

你真的Read()在调用 DataReader

while (res.Read())
{
    // something with res[x] field values here
}

请参阅 MSDN - http://msdn.microsoft.com/en-us/library/haa3afyz(v=vs.100).aspx

要么,要么您的查询没有任何结果。

根据您的编辑,您的参数值“应该”(基于您当前的设计,而不是最佳实践)

pars[0][2] = "IDString here"
于 2012-08-30T09:32:09.437 回答
0

好吧,看起来问题是 addWithValue() 将字符串转换为 NVARCHAR,我认为这在 WHERE 子句中造成了麻烦,因为我的字段是 VARCHAR 类型。显式类型转换解决了这个问题。

于 2012-09-03T08:03:01.200 回答