I’m trying to pass a data table to a stored procedure. The table has four columns, OldDifficulty, OldIndex, NewDifficulty, and NewIndex. It is passed to a stored procedure which is supposed to update all the rows in a Puzzles table changing rows with the old index and difficulty to their new index and difficulty. The Puzzles table does not change, and I can’t figure out why. I’m not sure whether the problem is in the code or in the database query.
Here is the C# code that calls the stored procedure:
var Form = context.Request.Form;
DataTable table = new DataTable();
table.Columns.Add("OldDifficulty");
table.Columns.Add("OldIndex");
table.Columns.Add("NewDifficulty");
table.Columns.Add("NewIndex");
foreach (var key in Form.Keys)
{
var Old = key.ToString().Split('_');
var New = Form[key.ToString()].Split('_');
if (Old == New || New.Length == 1 || Old.Length == 1) continue;
table.Rows.Add(Old[0], int.Parse(Old[1]), New[0], int.Parse(New[1]));
}
using (var con = new SqlConnection(SqlHelper.ConnectionString))
{
con.Open();
using (var com = new SqlCommand("RearrangePuzzles", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add(new SqlParameter("ChangedPuzzles", table)
{ SqlDbType = SqlDbType.Structured });
com.ExecuteNonQuery();
}
con.Close();
}
and here is the stored procedure:
ALTER PROCEDURE [dbo].[RearrangePuzzles]
@ChangedPuzzles ChangedPuzzlesTable READONLY
AS
UPDATE p
SET
NthPuzzle = cp.NewIndex,
Difficulty = cp.NewDifficulty
FROM
Puzzles p JOIN
@ChangedPuzzles cp ON cp.OldIndex = p.NthPuzzle AND cp.OldDifficulty = p.Difficulty
Do you have any idea why the table isn’t updating? Is there something wrong with my SQL?
Everything looks ok, except:
I would change to:
@sign – prefix in parameter name.Use SQL Server Profiler to see whether this query actually is executed.