【问题标题】:Pre check for data insertion预检查数据插入
【发布时间】:2012-06-14 01:54:01
【问题描述】:

我想制作一个值预检查程序。用户将向 UI 提供单个输入(wbslement no)。我想将该记录插入到 System 中。在插入数据库之前,我想检查它是否存在于表中。如果它存在于表中,那么它不应该将记录插入到表中,如果它不存在于数据库中,那么它应该插入。

目前在加载时,我正在从表中获取所有记录,之后我试图插入到系统中。

在我的代码中,无论如何都是插入值

            CrCon = new SqlConnection(spcallloggin);
            CrCon.Open();
            CrCmd = new SqlCommand();
            CrCmd.Connection = CrCon;

            CrCmd.CommandText = "GetOraderNumberDetail";
            CrCmd.CommandType = CommandType.StoredProcedure;

            sqladpter = new SqlDataAdapter(CrCmd);
            ds = new DataSet();
            sqladpter.Fill(ds);
            for (int count = 0; count < ds.Tables[0].Rows.Count; count++)
            {

                if (txtwbs.Text == ds.Tables[0].Rows[count][0].ToString())
                {
                            Lbmsg.Visible = true;
                            Lbmsg.Text = "Data Already Exists !";
                            count = count + 1;
                 }
                 else
                 {
                       insetreco(val);
                 }
             }

【问题讨论】:

标签: c# asp.net


【解决方案1】:

检查一下:

根据需要进行更改

IF EXISTS (SELECT 1 FROM targetTable AS t
 WHERE t.empNo = @yourEmpNo
     AND t.project = @yourProject)
BEGIN
   --what ever you want to do here
END
ELSE
BEGIN
  INSERT INTO yourTable (empno, name, project)
  SELECT @empno, @name, @project
END

【讨论】:

    【解决方案2】:

    最好直接在存储过程中查看。

    IF NOT EXISTS(SELECT * FROM [TABLE] WHERE unique_field = "value of the txtwbs")
    BEGIN
        INSERT INTO [TABLE]
        VALUES (value1, value2, value3,...)
    END
    

    你也可以改变你的代码如下:

    bool doesExist;
    for (int count = 0; count < ds.Tables[0].Rows.Count; count++)
    {
    
        if (txtwbs.Text == ds.Tables[0].Rows[count][0].ToString())
        {
              Lbmsg.Visible = true;
              Lbmsg.Text = "Data Already Exists !";
              doesExist = true;
              break;
        }
    }
    if(!doesExist)
        insetreco(val);
    

    【讨论】:

    • 如何在插入语句中写 where cluase ?
    【解决方案3】:

    只需对表本身进行“唯一”键约束。 MySQL 已经有一个现有的结构来处理这个问题,所以你的代码没有意义。

    【讨论】:

      【解决方案4】:

      您可以使用DataView's RowFilter 查询内存表:

      Dataview dv = ds.Tables[0].DefaultView ;
      dv.RowFilter="wbslement_no="+number;
      if(dv.ToTable().Rows.Count==0)
      {
            //insert into database 
      }
      else
      {
             Lbmsg.Visible = true;
             Lbmsg.Text = "Data Already Exists !";
      }
      

      或者

      您可以检查存储过程中的重复性,而不是两次单独调用数据库。

      【讨论】:

        猜你喜欢
        • 2014-10-04
        • 1970-01-01
        • 2023-04-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多