Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use insert and update command using c#

I have GridView and I am trying to check Task_ID from a table, if it is found then I want to update the record but if Task_ID is not found in the table then I want to insert it into my table. My code now does the insert part but it does not do the update part of the code. I was wondering how you can do this within the same code. Please help. thanks here is my code:

int index = 0;
foreach (GridViewRow row in myGV.Rows)
{
    if (row.RowType == DataControlRowType.DataRow)
    {

        Label ID = row.FindControl("lbl_ID") as Label;

        string UID = Request.Form[row.FindControl("hfUId").UniqueID];

        DateTime strDate = DateTime.Now;
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myCon"].ConnectionString);
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into myTable(TID, USR_ID, UPDT_DT) values(@ID, @USR_ID, @UPDT_DT) ";

        cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = ID.Text;
        cmd.Parameters.Add("@USR_ID", SqlDbType.VarChar).Value = UID.ToString();
        cmd.Parameters.Add("@UPDT_DT", SqlDbType.VarChar).Value = strDate.Date;
        cmd.Connection = con;
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        con.Dispose();
        cmd.Dispose();
    }

    index++;
}
like image 755
moe Avatar asked Nov 29 '25 21:11

moe


2 Answers

There is a MERGE command in SQL for this purpose. Here is an example that might work for you:

Merge myTable As T
    Using (Select Task_ID From myTable) As Src (Src_ID)
    ON (T.Task_ID = Src.Src_ID)
    WHEN MATCHED THEN
        UPDATE SET T.UPDT_DT = 'your new value'
    WHEN NOT MATCHED THEN   
        INSERT (TASK_ID, USR_ID, UPDT_DT)
        VALUES (@TASK_ID, @USR_ID, @UPDT_DT);

change 'your new value' to the correct update statement

like image 111
Milad.H Avatar answered Dec 02 '25 15:12

Milad.H


Replace the command text as below:

if not exists (select task_id from mytable where task_id = @task_id)  
insert into myTable(TASK_ID, USR_ID, UPDT_DT) values(@TASK_ID, @USR_ID, @UPDT_DT)
else
update mytable set USR_ID = @USR_ID, UPDT_DT = @UPDT_DT where task_id = @TASK_ID
like image 31
HOKBONG Avatar answered Dec 02 '25 13:12

HOKBONG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!