【问题标题】:ASP.NET , C# how to write this sql commandASP.NET , C# 如何编写这个 sql 命令
【发布时间】:2015-09-08 18:29:15
【问题描述】:

如何在 asp.net c# code behinds 中编写此代码?

我想要做的是选择invoicetable 中的所有行,orderno 等于当前session,并从与他们的 itemid 匹配的发票数量中扣除我的inventorytable 的库存。

SqlCommand cmd = 
    new SqlCommand("UPDATE inventorytable 
                    JOIN invoicetable ON inventorytable.ItemID = invoicetable.ItemID 
                    SET inventorytable.inventory = inventorytable.inventory-invoice.QTY 
                    WHERE invoicetable.No='" + Convert.ToInt32(Session["invoiceno"]) + "'"
                    , con);

InsertUpdateData(cmd); 

【问题讨论】:

  • 您提供的代码用于更新语句。您还想评估其他 SQL 吗?
  • 您的商品 ID 在哪里。你也把会话变量放进去吗?
  • 另外,您提供的 sn-p 存在一些相当严重的安全问题。
  • 查看参数。
  • 是的,我正在尝试通过减去 invoicetable 列 QTY 来减少每个项目的库存列来更新库存表

标签: c# sql asp.net sqlcommand


【解决方案1】:

您的更新查询格式不正确,您应该使用参数化 SQL。尝试使用类似的东西

var sqlQuery = 
    @"UPDATE inventorytable 
         SET inventorytable.inventory = inventorytable.inventory-invoice.QTY 
        FROM inventorytable
             INNER JOIN invoicetable ON inventorytable.ItemID = invoicetable.ItemID 
       WHERE invoicetable.No=@invNo";

using (var conn = new SqlConnection(CONN_STR))
{
   var sqlCmd = new SqlCommand(sqlQuery, conn);
   sqlCmd.Parameters.AddWithValue("@invNo", Session["invoiceno"].ToString());
   sqlCmd.ExecuteNonQuery();
}

我在没有 VS 的情况下输入了这个,所以如果有任何语法问题,请告诉我

【讨论】:

  • 我试过你的代码,它工作正常。你为我节省了很多时间,谢谢
【解决方案2】:
    var n = Session["invoiceno"] != null ? Convert.ToInt32(Session["invoiceno"]) : 0;

using (var conn = new SqlConnection(CONN_STR))
{
    conn.Open();
    var sql = "SELECT * FROM invoicetable WHERE orderno = @n";
    var cmd = new SqlCommand(sql);
    cmd.Connection = conn ;
    cmd.Parameters.AddWithValue("@n", n);

    using(var dr = cmd.ExecuteReader())
    {
        while(dr.Read())
        {
            //loop through DataReader
        }
        dr.Close();
    }
}

【讨论】:

    猜你喜欢
    • 2015-10-27
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多