0

下面是我想在更新数据库之前应用逻辑来减去 Quantity 的代码?我可以知道如何在代码中编写逻辑吗?好心提醒。

示例 WMWTContQTy.text 值[CIMProRPT01].[dbo].[WM_QTY_STATUS] CONTAINER_QTY在更新到 DB 表之前从 DB 值中减去

protected void WMWT_Submit(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            string TransID = WMWTNewID.Text;
            string Date = WMWTDATE.Text;
            string VendorName = WMWTVendorName.Text;
            string Material = WMWTMaterial.Text;
            string NetWeight = WMWTNetWeight.Text;
            string DocNum = WMWTDocNum.Text;
            string Status = WMWTStatus.Text;
            string Locator = WMWTLocator.Text;
            string ContainerQty = WMWTContQty.Text;
            string ContainerType = WMWTContType.Text;
            string ContainerSource = WMWTContSource.Text;
            string Remark = WMWTRemark.Text;
            string CreateDate = WMWTCDATE.Text;
            string CreateUser = WMWTCUSER.Text;

            string UpdateWMMRSQL = "UPDATE [CIMProRPT01].[dbo].[WM_QTY_STATUS] SET 
            STATUS = '" + Status + "',CONTAINER_QTY ='" + ContainerQty + "'";

            string InsertWMMRSSQL = 
            "INSERT INTO [CIMProRPT01].[dbo].[WM_TRANS_HISTORY] 
            (TRANSID,DATE,VENDOR_NAME,MATERIAL,NET_WEIGHT,DOC_NUM,STATUS,CONTAINER_QTY,
            CONTAINER_TYPE,CONTAINER_SOURCE,LOCATOR,REMARK,CREATEDATE,CREATEUSER)   
            VALUES ('" + TransID + "','" + Date + "','" + VendorName + "','" + Material 
            + "','" + NetWeight + "','" + DocNum + "','" + Status + "','" + 
            ContainerQty + "','" + ContainerType + "','" + ContainerSource + "','" + 
            Locator + "','" + Remark + "','" + CreateDate + "','" + CreateUser + "')";

            SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CIMProRPT01ConnectionString"].ConnectionString);

            SqlCommand Insertcmd = new SqlCommand(InsertWMMRSSQL, con);
            SqlCommand InsertHisscmd = new SqlCommand(UpdateWMMRSQL, con);

            con.Open();

            Insertcmd.ExecuteNonQuery();
            InsertHisscmd.ExecuteNonQuery();

            con.Close();

            Response.Redirect("WM_WT.aspx?stat=insert");
        }
    }
4

2 回答 2

1

您可以在更新语句本身中执行此操作

UPDATE [CIMProRPT01].[dbo].[WM_QTY_STATUS]
SET 
STATUS = '@Status',
CONTAINER_QTY = CONTAINER_QTY - '@Change'

使用参数化查询,这样您就不会受到 SQL 注入的影响

using(SqlCommand UpdateHisscmd = new SqlCommand(UpdateWMMRSQL, con))
{
  UpdateHisscmd.Parameters.AddWithValue("@Status", Status);
  UpdateHisscmd.Parameters.AddWithValue("@Change", WMWTContQTy.text);
  UpdateHisscmd.ExecuteNonQuery();
}
于 2013-06-13T06:32:58.870 回答
0

第一件事。根据您当前的设计,您可以实现以下相同:

string UpdateWMMRSQL = "UPDATE [CIMProRPT01].[dbo].[WM_QTY_STATUS] 
SET STATUS = '" + Status + "',CONTAINER_QTY = CONTAINER_QTY - '" + ContainerQty + "'";

但这是一个非常糟糕的设计,会导致您出现一些其他问题,例如SQL Injection. 所以最好使用参数化查询来避免这种情况,正如@nunespascal 的帖子中所解释的那样。

于 2013-06-13T07:32:23.440 回答