Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How does one trap the duplicate key error for SQL server?

Status
Not open for further replies.

kazai

Programmer
Oct 19, 2001
24
US
hi,
I wanted to know how one can trap the duplicate key error for SQL server? I have an insert statement, which throws up an error for duplicate insertions...how do I trap that error and display my own appropriate message....PLS. HELP!!!!! IT's VERY VERY URGENT!!!!!!!!
thanks,
Radhika.
 
Here's how I would go about this:

form.asp
-------------
<%@ Language=VBScript %>
<HTML>
<HEAD>
</HEAD>
<BODY>

<form name=&quot;test&quot; action=&quot;insert.asp&quot; method=&quot;post&quot;>
<input type=&quot;text&quot; name=&quot;pub_id&quot;>
<input type=&quot;text&quot; name=&quot;pub_name&quot;>
<input type=&quot;submit&quot;>
</form>

</BODY>
</HTML>


insert.asp
--------------

<%@ Language=VBScript %>
<HTML>
<HEAD>
</HEAD>
<BODY>

<%
dim ors,oconn,strsql,strconn
strconn = &quot;driver={SQL Server};server=server2000;uid=sa;pwd=;database=pubs&quot;
set oconn = server.CreateObject(&quot;ADODB.Connection&quot;)
oconn.Open strconn
strsql = &quot;Select pub_name from publishers where pub_id = '&quot; & request(&quot;pub_id&quot;)& &quot;'&quot;
set ors = oconn.Execute(strsql)
if not ors.eof then
Response.Write(&quot;This id already exists!!!!&quot;)
else
strsql = &quot;Insert into publishers (pub_id,pub_name) values ('&quot; & request(&quot;pub_id&quot;)& &quot;','&quot; & request(&quot;pub_name&quot;)& &quot;')&quot;
set ors = oconn.Execute(strsql)
if err.number = 0 then Response.Write &quot;Success!&quot;
end if
%>

</BODY>
</HTML>


Of course, this is just a sample, but it works. Just take care of closing and setting objects to nothing after using them.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top