this is my sp
CREATE PROCEDURE DeteleTitle ( @TitleID int ) AS BEGIN IF EXISTS(Select TitleID from Titles WHERE TitleID=@TitleID ) BEGIN DELETE FROM Titles WHERE TitleID=@TitleID SELECT @TitleID END ELSE BEGIN SELECT 0 END END
The method I call: -
public Int32 DeleteTitle(Int32 TitleID) { try { int ds=0; SqlParameter[] sqlparam=new SqlParameter[1]; sqlparam[0]=(@TitleID,TitleID); ds=Convert.ToInt32(SqlHelper.ExecuteScalar(ConfigurationManager.ConnectionStrings["con"].ConnectionString,CommandType.StoredProcedure,"DeleteTitle",sqlparam).Tables[0]); return ds; } catch(Exception ex) { return 0; } }
TitleID is now a foreign key in many tables. If a TitleID is used in any table entry, then it throws this exception, which says "Foreign key violation n". In my Stored Procedure above, I select zero in the else block if deletion fails. When delete IS is successful, it returns the TitleID value as 50, 99, or whatever. Now, what happens when the deletion fails, it does not return zero. I wanted the message to be displayed on the screen based on this null value returned by the Delete Saved method, but when it did not return any value (if the deletion failed), I returned zero in the catch block of my DeleteTitle () method.
Now I have two questions: -
- Why didn't the stored procedure return zero when the delete failed?
- Returns zero in a catch block, as I did above the correct path? I did not know how you extract the Exception number of the foreign key and so on, so I just went back there in catch catch.
source share