Hi
I have unique Index on Student field in Database sql. I want when Unique Index error comes , i want to display my own error 'Duplicate record found'
Thanks
Hi
I have unique Index on Student field in Database sql. I want when Unique Index error comes , i want to display my own error 'Duplicate record found'
Thanks
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Vishal YelvePosted Apr 13, 2023, 10:41 AM
Hi Ramco,
try this
if(ex.Message.Contains("UNIQUE KEY constraint"))
{
// your message
}
Tuhin PaulPosted Apr 16, 2023, 1:04 AM
You can also include the custom error message in a THROW statement
Tuhin PaulPosted Apr 16, 2023, 1:02 AM
Lets say you have a table named Students with a unique index on the StudentID field. You can catch the unique index violation error using a TRY...CATCH block in your SQL query like this
if the INSERT statement violates the unique index on the StudentID field, the error number 2601 will be raised. The IF condition in the CATCH block checks for this error number and raises a custom error message using the RAISERROR statement.
Tuhin PaulPosted Apr 16, 2023, 1:00 AM
You can catch the unique index violation error in your SQL query and replace the standard error message with your own custom error message.
Ramco RamcoPosted Apr 13, 2023, 10:36 AM
Hi AMit
It is giving message ex does not contain a definition for number
Thanks
Vishal YelvePosted Apr 13, 2023, 10:24 AM
Hi Ramco,
Do refer below link which shows complete implementaion
https://www.codeproject.com/Articles/1130113/Best-Ways-of-Implementing-Uniqueness-or-Unique-Key
else
Amit MohantyPosted Apr 13, 2023, 10:20 AM
Try this