3

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++;
}

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

I would first query the database to see if the task_id existed... declare cmd, define it with a sql command like "Select count(*) from myTable where Task_ID = '" & Task_ID.text & "'" and assign that to some variable x. Then follow that with "if x <> 0 then --> define your cmd as an insert statement here, ELSE --> define cmd as "Update myTable set blah blah = values WHERE task_ID = " & task_ID.text.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.