Thursday, March 29, 2012

Error reporting from SP to .NET code, how?

Hey

ASP.NET 2.0 + MS Sql Server 2005 Express (that version which comes with VS2005)

This code below fails. The Delete method executes a stored procedure, but somehow this SP fails. The SP shown here is a short version of the actual SP. As you see from the code below, there are no way the Delete method can know if SP executed successfully. I assume I just could have returned @.@.error, but that just gives an error number, and not the description of the error??.. And how should I capture exceptions like these?? How should code this SP so it report the error??

Any suggestions??

public override void Delete(System.Guid id, int user)
{
using (SqlConnection cn = new SqlConnection(this.ConnectionString))
{
SqlCommand cmd = new SqlCommand("SendMessage", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@.id", SqlDbType.UniqueIdentifier).Value = id;
cmd.Parameters.Add("@.user", SqlDbType.Int).Value = user;
}
}

ALTER PROCEDURE dbo.DeleteMessage @.id uniqueidentifier, @.user int
AS
BEGIN
UPDATE table_A set column_A = 1 WHERE Id = @.id;
DELETE FROM table_B WHERE Id = @.id;
IF (@.@.error = 0)
COMMIT TRAN;
ELSE
ROLLBACK TRAN;
END

there is a couple of way to report that what happened, you can use execute nonquery to get number of rows affected by last SQL command, you can return from your procedure single cell using SELECT with value 0 for success and 1 for error and finally you can use output parameters and read its values after procedure executes. See T-SQL help in SQL management studio express which is very good and you can find everything you wont.

No comments:

Post a Comment