I am trying to do following Insert Command .But it is not working neither showing any exception. Can anybody tell me where I am doing wrong thing?
using System;
using System.Data;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Security.Principal;
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void USP_tempSP()
{
DataTable objDataTable = new DataTable();
using (SqlConnection objConn = new SqlConnection("context connection=true"))
{
objConn.Open();
SqlCommand objCmd = new SqlCommand();
objCmd.CommandType = CommandType.Text;
objCmd.Connection = objConn;
objCmd.CommandText = "select * from temp";
/*table Structure
*CREATE TABLE [dbo].[temp]([empname] [varchar](20) NULL,[createdon] [datetime] NULL,[emp_id] [varchar](4) NULL
)
*/
SqlDataAdapter objDataAdapter = new SqlDataAdapter(objCmd.CommandText, objConn);
objDataAdapter.Fill(objDataTable);
SqlCommand objCmd1 = new SqlCommand();
objCmd1.CommandType = CommandType.Text;
objCmd1.UpdatedRowSource = UpdateRowSource.None;
objCmd.CommandText = "Insert into tempCopy " +
" values(@empname,@createdon)";
/*table Structure
*CREATE TABLE [dbo].[tempCopy]([empname] [varchar](20) NULL,[createdon] [datetime] NULL
)
*/
objCmd.Parameters.Add("@empname", SqlDbType.VarChar, 20, objDataTable.Columns["empname"].ColumnName);
objCmd.Parameters.Add("@createdon", SqlDbType.DateTime, 8, objDataTable.Columns["createdon"].ColumnName);
SqlDataAdapter adpt = new SqlDataAdapter();
adpt.InsertCommand = objCmd;
adpt.UpdateBatchSize = objDataTable.Rows.Count;
try
{
int recordsInserted = adpt.Update(objDataTable);
}
catch(Exception ex)
{
//
}
objConn.Close();
}
}
}
I really think this is because you are using the update method on an table which is tracking it’s own changes. The problem is that nothing has changed. Set
AcceptChangesDuringFill = falseso that the rows are marked as added to the table.I think this should work, you need to be more careful with your variable naming. objCmd is fairly meaningless. If the command has been cmdSelectData and cmdInsertData it would have been much clearer. Also pretty much everything is an object so obj just clutters up the code.