We help IT Professionals succeed at work.

inserting a record after turning identity on

adamtrask asked
The following code is part of a class in C# Windows application.
The code tries to insert a record into the distribution table. But because identity is off I have to turn it on, insert the record, and turn identity back off after the insertion is completed.

The records which is being inserted, is copied from another table called ClosedTickets.

After inserting the  copied record into the distribution table I need to delete it from the ClosedTickets table.

As you can see, I attempted to do it all in one method, which end in a syntax error near the key word "select".
This is the first time I use the identity statement.
Please correct me where I am going wrong. Thanks

  public void RestoreClosedTicket(Int32 ID)
            SqlConnection con = new SqlConnection();
             con = new SqlConnection("Server=PC;;Database=SupportProject;integrated security=True");
             SqlCommand commIDentityOn = new SqlCommand("Set Identity_Insert Distribution On", con);
             SqlCommand commIdentityOff = new SqlCommand("Set Identity_Insert Distribution off", con);
             SqlCommand comm = new SqlCommand("Insert into Distribution(ID,userID,dDate,tTime,sSubject,compName,TicketContent,desDepartmwnt)Values(Select * from  ClosedTickets where ID= @ID", con);
             SqlCommand commDelete = new SqlCommand("delete from ClosedTickets where ID = @ID", con);
             comm.Parameters.AddWithValue("@ID", System.Data.SqlDbType.Int);
             comm.Parameters["@ID"].Value = ID;
Watch Question

Contract ERP Admin/Consultant
When using a SELECT in an INSERT, you don't use the VALUES. Once you close out your explicit field list, simply start your SELECT.


Thank you.... but now I have syntax error near @ID

Here is how i rewrote the insert/select statement

  SqlCommand comm = new SqlCommand("Insert into Distribution(ID,userID,dDate,tTime,sSubject,compName,TicketContent,desDepartmwnt)(Select * from  ClosedTickets where ID= @ID", con);
dsackerContract ERP Admin/Consultant

@ID probably doesn't exist. You need to concatenate that on C# style.