在Asp.Net中计算

时间:2013-06-13 06:13:14

标签: asp.net sql database

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

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

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

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:0)

首先要做的事情。根据您当前的设计,您可以实现以下相同的目标:

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

但这是一个非常糟糕的设计,会引发一些其他问题,如SQL Injection。所以最好使用参数化查询来避免这种情况,如@nunespascal的帖子所述。