简体   繁体   English

ASP.NET,C#如何编写此sql命令

[英]ASP.NET , C# how to write this sql command

How can I write this code in asp.net c# code behinds? 如何在asp.net C#代码背后编写此代码?

Wwhat I'm trying to do is to select all rows in invoicetable with orderno that is equal to current session and deduct the inventory of my inventorytable from `invoicetable qty that matches their itemid's. Wwhat我试图做的是选择所有行invoicetableorderno等于当前session并扣除我的库存inventorytable从`invoicetable数量符合他们的itemid的。

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); 

Your update query is not formed correctly, and you should be using parameterized SQL. 您的更新查询格式不正确,应该使用参数化的SQL。 Try using something like this 尝试使用类似这样的东西

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();
}

I typed this without VS in front of me, so let me know if there are any syntax issues 我在没有VS的情况下输入了此内容,所以请告诉我是否存在语法问题

    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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM