SQL: Best practice for inserting a record if it doesn't exist - asp.net

I have an asp.net Gridview that handles insert operations into a SQL database. Records are only permitted to be inserted if they meet a uniqueness criteria, and this constraint is being enforced using unique indexes in SQL server. If the user attempts to insert a record that already exists, an error message is displayed.
I'm wondering what the best practice is for implementing this.
Check if the record exists SQL side, using IF EXISTS, and locking hints (updlock, holdlock, etc). Return an error code to ASP.net depending on whether the record was inserted
Perform the INSERT operation inside a SQL server try/catch block, relying on the unique index to prevent the insert from occurring if the record exists. Return an error code depending on whether an exception was thrown.
Perform the INSERT operation SQL side, but without SQL try/catch. Handle the PK violation exception inside ASP.net instead.
Normally I'd consider using exceptions to handle valid operations to be bad practice - i.e. software should not throw exceptions unless something is broken. However if the unique index on the table in SQL is going to implement the desired constraint, why bother performing a manual check for existence of the record?

I would make a separate call to check if the record already exists. If yes, show message to user, if no make insert. The reason I would do it this way is because I prefer keeping all the business logic in the application.
If you insist in making just one stored proc call:
I would check before I insert. I would also add an output parameter to the stored proc that returns a message if the insert was unsuccessful. In my application if I see a message in the output parameter, I will display that to the user.

Related

Cannot bind result of HTTPUtility method to session variables

I am using ASP.NET Web Forms. I am trying to bind some data from a previous page (including the URL and some specific figures stored in the URL) to session variables for use in a SQL insert statement to a SQL Server database.
An example of one of the assignments is below:
this.Session["URL"] = HttpUtility.ParseQueryString(Request.UrlReferrer.Query)["helpurl"];
The problem I am having is that on executing the SQL insert, the value does not seem to be present and the default value is recorded. SessionState is enabled. I am able to print the result of the HttpUtility method to a label, and I am also able to assign to session variables for a SQL statement if I assign them directly, eg:
this.session["Variable"] = Variable;
Any ideas why the result of the HttpUtility function may not be assigned to the session variable prior to the execution of the SQL insert statement?
It's ok - I placed the assignments inside an
if(!IsPostBack)
And they now work ok and are being recorded to the database. I also removed the 'this' keyword from them.
Thanks anyway

ORA-00001: unique constraint (ABC.XY_PK) violated Error

before inserting in the table i am validating if the ID already exists in table.
It does not exists. Even though it through this error. Is there any possibility that the table does not allow to insert may be permission issue.
I have that insert query in a procedure, is there a possibility that due to procedure permission it doesn't allow.
If you check in the first statement/transaction for existences and you run this SP in parallel it is possible that the second (INSERT) statement/transaction fails.
In this case you can use a MERGE statement which either inserts the data or updates on existences in one transaction.

Not able to insert again after System.Data.UpdateException >> Unique Key

I was working with LINQ in my asp.net application. I've putted a Unique Key on two columns of the 'ColorDV' table. When trying to add a duplicated value like 'ss' I've got the result:
System.Data.UpdateException: An error occurred while updating the
entries. See the inner exception for details. --->
System.Data.SqlClient.SqlException: Violation of UNIQUE KEY constraint
'TITLE_AR_ColorDV'. Cannot insert duplicate key in object
'dbo.ColorDV'. The duplicate key value is (ss). The statement has been
terminated.
but the problem is that after this exception i can't insert any record in any of the tables, because of the same exact exception. I wonder if LINQ is trying to perform the same previous insert each time.
Please how can I solve this problem?
When you add an object to the ObjectContext, that object stays within the list of objects being submitted to the database, so yes that is the problem. Remove the object and continue, or if an edit try to use the Refresh method on the context to refresh the contents of the object to the original state.
This has an additional approach; can't personally say it works though.

parsing SQLException errors in an ASP.NET (MVC) application?

While validation can prevent most SQL errors, there are situations that simply cannot be prevented. I can think of two of them: uniqueness of some column and wrong foreign key: validation cannot be effective as the an object can be created or deleted by other parties just after validation and before db insertion. So there are (at least) two SQL errors that should lead to a message of invalid user input.
SQLException has a Number property for the error type, but I don't know how to find out which column is duplicated or which foreign key is wrong without trying to parse the actual error message text, which happens to be localized.
Is there any way to identify the offending column other than parsing the error message (which means at least to strictly choose a language for SQL Server and always use it)?
edit:
I should mention that I come from RubyOnRails, where the approach is: let's pretend that the db doesn't exist: no constraints, no db-enforced foreign keys etc. As I'm approaching ASP.NET MVC, I'd like to get rid of the rails biases, and accept the fact that the db indeed exists.
Are you sure these two situations absolutely cannot be prevented?
You can avoid unique constraint SQLexceptions on Insert, by using an Identity (database generated) primary key column. SQL Server will guarantee that the value is unique.
The same goes for inserting related rows into tables linked by a foreign key. Insert a row in each referenced table first, before inserting a row in the main table. Use IDENTITY_INSERT to get the value of each auto generated primary key and use this as the foreign key in your main table.
You should also wrap these individual statements in a transaction to ensure that either all tables are inserted successfully or none are. The transaction also isolates (hides) these changes from all other concurrent database accesses until the transaction is committed.

Handling Constraint SqlException in Asp.net

Suppose I have a user table that creates strong relationships (Enforce Foreign Key Constraint) with many additional tables. Such orders table ..
If we try to delete a user with some orders then SqlException will arise.. How can I catch this exception and treat it properly?
Is this strategy at all?
1) first try the delete action if an exception Occur handel it?
2) Or maybe before the delete action using code adapted to ensure that offspring records throughout the database and alert according to .. This piece of work ...
So how to do it?
--Edit:
The goal is not to delete the records from the db! the goal is to inform the user that this record has referencing records. do i need to let sql to execute the delete command and try to catch SqlException? And if so, how to detect that is REFERENCE constraint SqlException?
Or - should I need to write some code that will detect if there are referencing records before the delete command. The last approach give me more but its a lot of pain to implement this kind of verification to each entity..
Thanks
Do you even really want to actually delete User records? Instead I'd suggest having a "deleted" flag in your database, so when you "delete" a user through the UI, all it does is update that record to set the flag to 1. After all, you wouldn't want to delete users that had orders etc.
Then, you just need to support this flag in the appropriate areas (i.e. don't show "deleted" users in the UI).
Edit:
"...but just for the concept, assume that i do want delete the user how do i do that?"
You'd need to delete the records from the other tables that reference that user first, before deleting the user record (i.e. delete the referencing records first then delete the referenced records). But to me that doesn't make sense as you would be deleting e.g. order data.
Edit 2:
"And if so, how to detect that is REFERENCE constraint SqlException?"
To detect this specific error, you can just check the SqlException.Number - I think for this error, you need to check for 547 (this is the error number on SQL 2005). Alternatively, if using SQL 2005 and above, you could handle this error entirely within SQL using the TRY...CATCH support:
BEGIN TRY
DELETE FROM User WHERE UserId = #MyUserId
END TRY
BEGIN CATCH
IF (ERROR_NUMBER() = 547)
BEGIN
-- Foreign key constraint violation. Handle as you wish
END
END CATCH
However, I'd personally perform a pre-check like you suggested though, to save the exception. It's easily done using an EXISTS check like this:
IF NOT EXISTS(SELECT * FROM [Orders] WHERE UserId=#YourUserId)
BEGIN
-- User is not referenced
END
If there are more tables that reference a User, then you'd need to also include those in the check.

Resources