-1

I have a C# program from which I want to execute

Insert into table 
   Select * from table2

Here's the code I have

using (SqlConnection conn = new SqlConnection(ConfigurationManager
                            .ConnectionStrings["SQLConnectionString2"].ConnectionString))
{
    conn.Open();

    string selectStmt = "INSERT INTO [TestDB].[dbo].[Test] (ID, Name, CreatedDate) " +
                        "SELECT TOP 10 [ID], [Name], [CreatedDate] FROM [TestDB].[dbo].[TempOrig]";

    using (SqlCommand cmd2 = new SqlCommand(selectStmt, conn))
    {
        int resultValue = cmd2.ExecuteNonQuery();
        Console.WriteLine(resultValue.ToString());
    }

    conn.Close();
}

I do not see any rows being insert to [TestDB].[dbo].[Test] and neither there is an error.

I am not sure what is happening.

Thanks MR

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user2726975
  • 1,285
  • 3
  • 17
  • 26

1 Answers1

1

You problem is that you are only inserting rows, Your sql query isn't returning any rows, it is a simple insert.

But if you used OUTPUT clause with your insert you will be able to see the rows that were inserted.

Another thing to watch out is that a table will be returned by the OUTPUT clause in your SQL query, so you cannot use the int resultValue variable to capture the results, you will need a DataTable object.

Things to do:

  1. Modify the SQL Query to add OUTPUT clause.
  2. Create a DataTable object.
  3. Fill the DataTable object with the result set returned by the insert.
  4. Finally read from DataTable object and display on the console.

string conString = "Server=ServerName;Database=DBName;User Id=UserName;Password =********; ";
string sqlcmd = " INSERT INTO [TestDB].[dbo].[Test] (ID, Name, CreatedDate) "
              + " OUTPUT inserted.ID, inserted.Name, inserted.CreatedDate "
              + " SELECT TOP 10 [ID], [Name], [CreatedDate] FROM [TestDB].[dbo].[TempOrig] ";

using (SqlConnection con = new SqlConnection(conString))
{
    using (SqlCommand cmd = new SqlCommand(sqlcmd, con))
    {
        con.Open();

        // fill in the DataTable object
        DataTable dt = new DataTable();
        using (var insertedOutput = cmd.ExecuteReader())
        {
            dt.Load(insertedOutput);
        }


        // Read from DataTable object and print on the console
        DataRow[] currentRows = dt.Select(null, null);

        if (currentRows.Length < 1)
            Console.WriteLine("No Current Rows Found");
        else
        {
            foreach (DataColumn column in dt.Columns)
                Console.Write("\t{0}", column.ColumnName);

            Console.WriteLine("\t");

            foreach (DataRow row in currentRows)
            {
                foreach (DataColumn column in dt.Columns)
                    Console.Write("\t{0}", row[column]);

               Console.WriteLine("\t");
            }
        }
        Console.ReadLine();
    }
}
M.Ali
  • 67,945
  • 13
  • 101
  • 127