简体   繁体   English

带条件的SQL Server存储过程

[英]SQL Server stored procedure with condition

I'm trying to create a conditional event when I press an <asp:button> in C#. 当我在C#中按下<asp:button>时,我试图创建一个条件事件。

I have a GridView related to two database tables (in SQL Server). 我有一个与两个数据库表(在SQL Server中)相关的GridView I should insert different values in one of them, every day. 我应该每天在其中一个中插入不同的值。

Inside the GridView : GridView内部:

  • I have a BoundField with the ID for each item inside the database table 我有一个BoundField ,其ID为数据库表中的每个项目
  • I have two TemplateFields with a textbox, named StartGV and EndGV 我有两个带有文本框的TemplateFields ,分别名为StartGVEndGV

Outside the GridView : GridView之外:

  • I have an <asp:TextBox> with an AjaxCalendarExtender . 我有一个<asp:TextBox>和一个AjaxCalendarExtender There I should select the date. 我应该在那里选择日期。 The textbox is TextDate 文本框是TextDate

So, when I press the <asp:button> , the event should: 因此,当我按下<asp:button> ,该事件应为:

  • check for each row in the Gridview (with the ID from the GridView 's first column and the date selected in the textbox outside the GridView ) if the record already exists in the database 检查在各行Gridview (与IDGridView的第一列和在外部的文本选择的日期GridView )如果记录在数据库中的已存在

    • If yes, the database record should be updated with the new values 如果是,则应使用新值更新数据库记录
    • If no, the a new record should be inserted with the values 如果否,则应使用值插入新记录

I'm using stored procedures for update and insert. 我正在使用存储过程进行更新和插入。

This is the code in C#: 这是C#中的代码:

protected void BotonSubmit_Click(object sender, EventArgs e)
{
        foreach (GridViewRow row in GridView1.Rows)
        {
            //HERE I SAVE THE TEXTBOXS FROM GRIDVIEW INSIDE A VARIABLE
            TextBox StartGV = row.FindControl("StartGV") as TextBox;
            TextBox EndGV = row.FindControl("EndGV") as TextBox;
            DateTime Date = DateTime.ParseExact(TextDate.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture);

            //HERE I EXTRACT THE VALUE FROM THE FIRST COLUMN (THE ID)
            if (row.RowType == DataControlRowType.DataRow)
            {
                string ID = row.Cells[0].Text;

            //HERE I CHECK IF THE ROW ALREADY EXISTS IN DATABASE TABLE:

                //IF YES, UPDATE:
                if (CADCATOPS.CADBatchHandoff.CheckTableDB(Convert.ToInt32(ID), Convert.ToString(Date)))
                {
                    string connectionString = @"MY CONNECTION STRING";
                    SqlConnection Connection1 = null;
                    SqlTransaction Transaction1 = null;
                    {
                        Connection1 = new SqlConnection();
                        Connection1.ConnectionString = connectionString;
                        Connection1.Open();
                        Transaction1 = Connection1.BeginTransaction(System.Data.IsolationLevel.Serializable);
                        SqlCommand command1 = new SqlCommand("UPDATE", Connection1, Transaction1);
                        command1.CommandType = CommandType.StoredProcedure;
                        command1.Parameters.Clear();
                        command1.Parameters.AddWithValue("@Start", Convert.ToDateTime(StartGV.Text));
                        if (EndGV.Text != "")
                        {
                            command1.Parameters.AddWithValue("@End", Convert.ToDateTime(EndGV.Text));
                        }
                        command1.ExecuteNonQuery();
                        Transaction1.Commit();
                        Connection1.Close();
                    }
                }

                //IF NO, INSERT:
                if (!CADCATOPS.CADBatchHandoff.CheckTableDB(Convert.ToInt32(IDBatch), Convert.ToString(FechaCT1)))
                {
                    //FIRST OF ALL, CHECK IF THE "STARTGV" TEXTBOX IS NOT EMPTY. IF IT'S EMPTY, THE PROCESS WILL NOT START FOR THIS ROW.
                    if (StartGV.Text != "")
                    {
                        string connectionString = @"MY CONNECTION STRING";
                        SqlConnection Connection1 = null;
                        SqlTransaction Transaction1 = null;
                        {
                        Connection1 = new SqlConnection();
                        Connection1.ConnectionString = connectionString;
                        Connection1.Open();
                        Transaction1 = Connection1.BeginTransaction(System.Data.IsolationLevel.Serializable);
                        SqlCommand command1 = new SqlCommand("INSERT", Connection1, Transaction1);
                        command1.CommandType = CommandType.StoredProcedure;
                        command1.Parameters.Clear();
                        command1.Parameters.AddWithValue("@Start", Convert.ToDateTime(StartGV.Text));
                        if (EndGV.Text != "")
                        {
                            command1.Parameters.AddWithValue("@End", Convert.ToDateTime(EndGV.Text));
                        }
                        comando.Parameters.AddWithValue("@ID", Convert.ToInt32(ID));
                        comando.Parameters.AddWithValue("@DATE", Convert.ToDateTime(DATE.Text));
                        command1.ExecuteNonQuery();
                        Transaction1.Commit();
                        Connection1.Close();
                        }
                    }
                }
            }
        }
    }

So, this is working but something is wrong: 因此,这是可行的,但是出了点问题:

  • The INSERT condition works fine. INSERT条件工作正常。

  • The UPDATE is not working ok: the "StartGV" and EndGV" values selected for the process is ALWAYS the same as the last row. This is not happening with the INSERT process. UPDATE无法正常进行:为该进程选择的“ StartGV”和“ EndGV”值始终与最后一行相同,而在INSERT进程中则不会发生这种情况。

Why could it be? 为什么会这样呢?

Edit 编辑

I forget to show the SELECT statements in my project: 我忘了在项目中显示SELECT语句:

Inside the table adapter, I have created this query, named CheckTableDB : 在表适配器内部,我创建了一个名为CheckTableDB查询:

SELECT COUNT(*) 
FROM BatchDatos 
WHERE (ID = @ID) and (DATE=@DATE)

And then, in c#: 然后,在C#中:

public static bool CheckTableDB(int ID, string DATE)
{
    return adapter.CheckTableDB(ID, DATE) != 0;
}

I use this for UPDATE and INSERT . 我将其用于UPDATEINSERT It's working ok for INSERT , that means the issue is not here. INSERT正常工作,这意味着问题不在这里。

Without condition where you update all rows in the table. 无条件更新表中的所有行。 You need to use ID from your GV to update exact row in the DB. 您需要使用GV中的ID来更新数据库中的确切行。

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

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