【问题标题】:How to count filtered rows with where clause in t-sql?如何使用 t-sql 中的 where 子句计算过滤的行?
【发布时间】:2015-08-21 05:14:15
【问题描述】:

鉴于下表。我需要使用事务处理 SQL 计算 SubCategory 列中的值为“Children's Books”的每条记录的行数。在这种情况下,我预计结果为 2。我尝试了类似的方法

SqlCommand cmd = new SqlCommand("Select Count(*) From [DisplayCenterTab] Where [SubCategory ]= '" + subcateg + "' ", con);

但它返回零(0)结果而不是 2。我在这里缺少什么?谢谢

我的桌子:

Id        ProductId       ProductName      Category            SubCategory
34534     34643645        dfhfsjfdjgh      sdfagdsfhfhgfhj     dfgsdhhgfh
45234     456436          fghdfjfgj        dfgsdhfhfgfgh       Children's Books
46536     45646           fgjdgjfgh        dfgshfgfdghj        Children's Books
43645     466456          systyerttry      sdhdfhfggjh         dfhshfdjgfgh
34526     456345          areyruuty        dfshfdfgjghj        dafgshfghgfh

更新

JQuery 代码

$("#sellstuff").click(function () {
    var dataObject = $("#scrolldummy").text();
    //var dataObject = "Children's Books";
    $.getJSON("/OnlineStore/TotalNumberofSubCateg", dataObject, function (data) {
        $("#search").val(data + " Assorted Items for Sale.");
    });
})

C#代码

[HttpGet]
        public JsonResult TotalNumberofSubCateg(string subcateg)
        {
            int rowcount;
            string constr = ConfigurationManager.ConnectionStrings["StockConnString"].ConnectionString;
            SqlConnection con = new SqlConnection(constr);
            con.Open();

            SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM DisplayCenterTab Where SubCategory = '"+ subcateg +"' ", con);

            cmd.CommandType = CommandType.Text;
            rowcount = Convert.ToInt32(cmd.ExecuteScalar());
            con.Close();
            return Json(rowcount, JsonRequestBehavior.AllowGet);
        }

【问题讨论】:

  • 你如何调用它并捕获返回值?可以发一下代码吗?
  • @felix Pammitan 我在 C# 中使用 json 结果返回值和 jQuery $.getJSON({...}) 命令。你想看看他们吗?
  • 那肯定有帮助。请发布 C# 代码。
  • 嘿菲利克斯,请看我的更新。谢谢
  • 请使用调试模式检查子类别的值。

标签: c# jquery mysql sql tsql


【解决方案1】:

您需要从subcateg 变量中转义单引号字符。 试试这个

    SqlCommand cmd = 
new SqlCommand("Select Count(*) From [DisplayCenterTab] Where [SubCategory ]= '" + subcateg.Replace("'","''") + "' ", con);

【讨论】:

  • 我也试过了,但它返回一个空值。
  • 这很奇怪。为count 返回null 很奇怪。您是否尝试查看在运行时准备的查询?
  • 是的,我认为我的客户端脚本中缺少某些内容。我现在正在密切关注它。
  • 你仍然需要我的回答中建议的修复来转义单引号',否则它会给你意想不到的输出
  • 你知道这有点奇怪。如果我尝试 subcateg.Replace("'","''") 它将给出一个空值。如果我只是错过了 Replace 方法,它将返回 0 值……嗯。我在这里怀疑我的客户端脚本。
【解决方案2】:

在查询中使用命令参数总是更好,它可以处理所有事情。这是您重写的代码:

    public JsonResult TotalNumberofSubCateg(string subcateg)
    {
        int rowcount;
        string constr = ConfigurationManager.ConnectionStrings["StockConnString"].ConnectionString;
        SqlConnection con = new SqlConnection(constr);
        con.Open();
        SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM DisplayCenterTab Where SubCategory = @S0 ", con);

        cmd.Parameters.AddWithValue("@S0", subcateg ); // it will handle the string format
        cmd.CommandType = CommandType.Text;
        rowcount = Convert.ToInt32(cmd.ExecuteScalar());
        con.Close();
        return Json(rowcount, JsonRequestBehavior.AllowGet);
    }

通常,这应该可以,但我还没有测试过。

【讨论】:

  • 所以让我用存储的专业测试它们..让我们看看它是否有效..等等
  • 不,它仍然会返回空值。我不确定为什么它没有捕获名为 subcate 的字符串参数。
  • 首先检查行数是否大于 0,如果是,则返回 json 行有问题。如果rowcount = 0,那么你的查询不好
【解决方案3】:

您需要在SQL 中将您的单引号 ' 替换为双引号 '',例如:

    SqlCommand cmd = 
new SqlCommand("Select Count(*) From [DisplayCenterTab] Where [SubCategory ]= 'Children''s Books' ", con)

【讨论】:

  • 让我更新我的代码以使用 C# 和 jquery 中的 json 结果调用和捕获值。Hold on
【解决方案4】:

伙计们..这实际上是我的烂摊子。这是我的问题的更新。我的 sql 语句实际上没有问题,但它实际上是我的客户端脚本变量声明。我忘了记住,在您的客户端脚本中,您的 dataObject 变量应该有您的类模型变量。我发布此更新,因此任何不知道或尚未遇到此类问题的人都会提前知道他们。

 $("#sellstuff").click(function () {

    var dataObject =
        { SubCategory: $("#scrolldummy").text() };

    $.getJSON("/OnlineStore/TotalNumberofSubCateg", dataObject, function (data) {
        $("#search").val(data + " Assorted Items for Sale.");
    });

})



 [HttpGet]
    public JsonResult TotalNumberofSubCateg(string SubCategory)
    {
        int rowcount;
        string constr = ConfigurationManager.ConnectionStrings["StockConnString"].ConnectionString;
        SqlConnection con = new SqlConnection(constr);
        con.Open();

        SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM DisplayCenterTab Where SubCategory = '"+ SubCategory.Replace("'","''") +"' ", con);

        cmd.CommandType = CommandType.Text;
        rowcount = Convert.ToInt32(cmd.ExecuteScalar());
        con.Close();
        return Json(rowcount, JsonRequestBehavior.AllowGet);
    }

【讨论】:

    猜你喜欢
    • 2016-12-09
    • 2011-02-25
    • 2019-10-06
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多