Catch duplicate primary key exeption

A

ad

The code below can only catch common excption.
I want to catch duplicate primary key exeption and do something more.

How can I catch duplicate primary key exeption

try
{
Insert a record to table
}
catch (????)
{
Do some thing more
}
catch (Exception err)
{
Label1.Text=err.Message;
}
 
M

Marina

You catch a SqlException. Although that can be thrown for any number of
reasons. You would have to examine the collection of errors inside it, and
see the number to see exactly why the exception was thrown.
 
H

hashimisayed

How is the primary key created? Is it auto generated? If so, you
wouldn't have this problem, so I am guessing that you are generating it
yourself. Can you tell us how the key is generated? You also need to
tell us how you are doing the insert? Is all of this done in code,
i.e., do you create a key in code and then try to do an insert? Or do
you use stored procedures for all of this? Tell us a little bit more...

sayed
 
H

hashimisayed

If you are doing the insert via a stored procedure, you can do a
"count(id) from mytable" and see if that is greater than zero. If so,
do a "raise error 'social insurance id already exists'". If you are not
inserting with a stored procedure, you have to do the count statment or
a select statement to figure out if the social exists and throw a
similar exception.

sayed
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,767
Messages
2,569,571
Members
45,045
Latest member
DRCM

Latest Threads

Top