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:
- Modify the SQL Query to add
OUTPUT
clause.
- Create a DataTable object.
- Fill the DataTable object with the result set returned by the insert.
- 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();
}
}