Question

Increase ID Once I delete from the table

Asked by: RickyGtz

Hello I have a table called tournament which has TourID as the primary key . When testing scenarios I found out a bug on my page  . When I delete using the following querie , then I insert a new tournament , I get the same TID, and I dont want this to happen I want to avoid any bugs caused by that, So How would I make the next tournametnt inserted be different ID thatn previous.,  


On new Tour ID

      Set RecSet = Server.CreateObject("ADODB.RecordSet")
            SqlQuery =  "Select max(TourID) from tblTournament"
            RecSet.Open SqlQuery,conSQL,1,1

            If isnull(RecSet(0)) Then
                  MAX_TourID = 1
            Else
                  MAX_TourID = 1 + RecSet(0)
            End if

if (request("action")="delete") then 
		conSQL.execute("delete from  tblTournament where TourID="&request("TId")&"")
		
		' I need to increase by two or tree TourID number to the next registered tournament...

                                  
1:
2:
3:
4:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-12-17 at 10:11:37ID23992854
Tags

ASP

,

SQL Server

Topics

Active Server Pages (ASP)

,

SQL Server 2005

,

JavaScript

,

SQL Query Syntax

,

MS SQL Server

Participating Experts
4
Points
500
Comments
20

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. KNIGHTS TOUR
    I have had to summit the question again because i cannot edit the question i set earlier cookies problem but here it is again a bit clearer to understand i hope Knights tour problem I need the design for a 2d array for where the user inputs the starting position for the kn...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: faiga16Posted on 2008-12-17 at 10:14:27ID: 23196228

Set the column as identity.  This is on Database level.

 

by: hibridassassinPosted on 2008-12-17 at 10:31:45ID: 23196433

Right click on the table and select modify..then select the colum you want to edit then look at colum properties...look for Identity Specification then click the plus sign and change (Is Identity) to yes and then crtl-s.

That will fix your problem.  I walked you through the steps of using Microsoft SQL Server Management Studio.

 

by: RickyGtzPosted on 2008-12-17 at 11:29:48ID: 23197061

Hi I tried that but that value can't be changed..

 

by: hibridassassinPosted on 2008-12-17 at 12:02:37ID: 23197370

its a bit confusing but when you go to (IS IDENTITY) you may have to scroll to the right and click on the box with the down arrow and choose either yes or no from the drop down menu...basically you can't type it. You have to choose yes or no from a drop down and depending on your monitor size and resolution it may be hidden so you have to scroll to the right.

 

by: RickyGtzPosted on 2008-12-17 at 12:35:52ID: 23197792

Yes I see identity specification
is identity
identity increment
identiy seed

but those fields are transparent cant choose or change

 

by: RickyGtzPosted on 2008-12-17 at 12:42:39ID: 23197893

I was readoing upon that and find out I cant change this to an existing column So I had to Create Aonther One and set the properties for this one...

 

by: hibridassassinPosted on 2008-12-17 at 13:01:29ID: 23198141

that's odd...I've been able to do that for existing columns in my tables...well, did you get everything working?

 

by: RickyGtzPosted on 2008-12-17 at 13:18:18ID: 23198287

Well I am testing if this will prevent that when I delete a tourid then I insert a new tournament ,get the same TID, .. Also I am concerned about this became read only, and I think some of my pages require to update this column...

 

by: hibridassassinPosted on 2008-12-17 at 13:34:03ID: 23198445

If you use the identity and increment them by 1 or whatever you choose, after you delete a row, the new tournament should not get the same TID....and it doesn't become read only but I don't understand why any of your pages would ever want to update that field because the whole point of the identity is to have the numbers in that column be unique....which leads me to my next question, do you already have an identity specification in the table and you just want another column to auto increment as well?

 

by: RickyGtzPosted on 2008-12-17 at 13:39:37ID: 23198498

i am not an expert on sql but i made tourid autoincrement 1  and is identiy yes

 

by: RickyGtzPosted on 2008-12-17 at 13:53:33ID: 23198639

When I insert a tournament it shows ..

Microsoft OLE DB Provider for ODBC Drivers error '80040e14'

[Microsoft][SQL Native Client][SQL Server]Cannot insert explicit value for identity column in table 'tblTournament' when IDENTITY_INSERT is set to OFF.

/admin/Tournaments/ad_touradd.asp, line 219

 

by: RickyGtzPosted on 2008-12-17 at 14:11:47ID: 23198799

This is fixed if explicitly turn Identity_Insert on and off before and after each insert.

SET IDENTITY_INSERT [ database. [ owner. ] ] { table } { ON | OFF }

But,,, Is there any way to avoid this

 

by: RickyGtzPosted on 2008-12-17 at 16:00:00ID: 23199573

Welll,,, Just tried the proposed solution but still I am geeting the new tournametn ID equal to the last tournament ID deleted....

 

by: RickyGtzPosted on 2008-12-17 at 16:02:54ID: 23199593

Do I need to add some code when Deleteing the Tournament?

 

by: hibridassassinPosted on 2008-12-18 at 08:11:49ID: 23204682

no, if you want send me a copy of you the table or the database and i'll take a look at it.  I think that will be the quickest way to do it...of course take out any sensitive data.

 

by: RickyGtzPosted on 2008-12-18 at 09:17:38ID: 23205349

HI this the asp that I use to delete  an user for the database.

<%response.buffer=true%>
<% level="../../"%>
<!-- #include file="../logincheck.asp"-->
<!--#include file="../include/intialize.inc"-->
<!--include file="../include/connection.asp"-->
<!--#include file="../../../Connections/sqlConn1.asp" -->
 
<%
' To delete Category from table
 
' To make Member Active/Deactive
 
	if (request("status")<>"") then 
	
		' Here I keeped the same format, the same variables and recordser 
			' BUT it is now looking to the connection String called conSQL 
			' which is equivalent to con (Access) , and is defined on sqlConn1.asp 
	
conSQL.execute("update tblTournament set TourVerify="&request("status")&" where TourID="&request("TId"))
	end if
		'con1.execute("update tblauthor set Active = 1 where username='"&request("SSN")&"'")
		
	if (request("action")="delete") then 
		conSQL.execute("delete from  tblTournament where TourID="&request("TId")&"")
		
		' I need to increase te TourID number to the next registered tournament...
		
		
		msg="Delete Successfully"
		response.redirect "ad_tourlist.asp?msg="&msg
	end if 
%>
<html>
<head>
<title><%=PageTitle%></title>
<meta http-equiv="content-Type" content="text/html; charset=iso-8859-1">
<link href="../style/style.css" rel="stylesheet" type="text/css">
</head>
<script language=Javascript>
function del_tournament(TourId)
{
	delconfirm = confirm("Are you Sure To delete this Record Permanently ?");
	if (delconfirm)
		window.location = "ad_tourlist.asp?action=delete&TId="+TourId;
		
}
</script>	
 
<body background="<%=level%>images/bg.jpg" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<table width="740" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr> 
    <td><!--#include file="../include/header.asp"--></td>
  </tr>
  <tr> 
    <td height="380" valign="top" bgcolor="#ffffff"> 
      <%
	if (session("adminname")<>"") then 
	%>
      <!--#include file="../include/loggedmenu.asp"--> <%
	end if	
	%> <br> <table width="90%" border="0" align="center" cellpadding="0" cellspacing="0"> 
<tr> <td align="center" class="errtext"><%=request("msg")%></td></tr> </table><br> 
<%
	 	    dim rs
			set rs = server.createobject("ADODB.Recordset")
			sql="select * from tblTournament"	
			rs.open sql,conSQL,1,1
			if rs.BOF then 
	  %> <table width="80%" border="0" align="center" cellpadding="0" cellspacing="0"> 
<tr> 
          <td align="CENTER" class="errtext">No Tournament is Found</td>
        </tr><tr><td align="RIGHT" class="errtext">&nbsp;</td></tr><tr ALIGN="CENTER">
          <td class="errtext"><A HREF="ad_touradd.asp">Add New Tournament</A></td>
        </tr> </table><%else%> <table width="75%" border="0" align="center" cellpadding="0" cellspacing="0"> 
<tr> 
          <td align="left"  class="text" width="76%">* To View Tournaments click 
            over the Tournaments Name listed</td>
          <td align="RIGHT"  class="text" width="24%"><A HREF="ad_touradd.asp">Add 
            New Tournaments</A></td>
        </tr> 
</table>
      <table width="75%" border="1" align="center" cellpadding="5" cellspacing="0" bordercolor="#5eb020" bordercolordark="#FFFFFF" bordercolorlight="#5eb020">
        <tr class="tableheader1"> 
          <td  width="64%">Tournaments Name </td>
          <td colspan="2" align="center">Action</td>
        </tr>
        <%
			do while Not rs.EOF 
			Tourname = rs("TourName")		
			TourId = rs("TourID")
			mstatus=rs("TourVerify")		
			if (i mod 2)=0 then
				bgcolor="#ffffff"
			else	
				bgcolor="#e6ffe6"
			end if
			
			if (mstatus=0) then 
		    statuslink="[<a href='ad_tourlist.asp?TId="&TourId&"&status=1' class='hlink3'>DeActive</a>]"
			else
			statuslink="[&nbsp;&nbsp;<a href='ad_tourlist.asp?TId="&TourId&"&status=0' class='hlink3'>Active</a>&nbsp;&nbsp;]"
			end if			
			
		%>
        <tr bgcolor="<%=bgcolor%>" width=15 class="text"> 
          <td align=left class="text2" width="64%"><a href="ad_touredit.asp?TId=<%=TourId%>" class="hlink3"><%=Tourname%></a></td>
          <td align=left class="text2" width="14%"><%=statuslink%></td>
          <td align=center width="22%" class="text"> [<a href="javascript: del_tournament('<%=TourId%>')" class="hlink3">Delete</a>] 
            [<A HREF="ad_touredit.asp?TId=<%=TourId%>" CLASS="hlink3">Edit</A>] 
          </td>
        </tr>
        <%
		i = i + 1
		rs.movenext
		loop
		end if
		%>
      </table>
    </td></tr> <tr> <td colspan="2"><!--#include file="../include/footer.asp"--></td></tr>
</table>
</body>
</html>
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:

Select allOpen in new window

 

by: AaronAbendPosted on 2008-12-24 at 05:19:20ID: 23239874

identity columns always increment their values. If you started as a non-identity and want to change to identity, you have to do the following.

Assume a simple
create table  mytable(mykey int , myvalue char(12))

insert into mytable select 1,'a'
insert into mytable select 2,'b'
insert into mytable select 3,'c'

Assume 150 rows in the table right now with max mykey=150

create table mynewtable (mykey int identity(1000,1), myvalue char(12))
set identity_insert mynewtable on
insert into mynewtable (mykey,myvalue) select mykey, myvalue from mytable
set identity_insert mynewtable off

now the next value for mykey will be 1001 and it will continue to increment thereafter.

insert into mynewtable(myvalue) values ('asdf')
select * from mynewtable
1      a          
2      a          
3      a          
1001      asdf        

Important Note!  you cannot include the key in your insert statement - leave it out and it will automatically increment

 

by: mark_willsPosted on 2008-12-24 at 07:37:40ID: 23240457

You won't be able to change an existing column to identity, so, will have to add it afresh...

The problem will then become, you cannot maintain it directly, which does mean you will have to take out the calculation to generate a new number, and remove it from your insert statements, nor can it be the object of an update (meaning cannot do things like update tblTournament set TourID= some_new_number ).

Your alternative would be to add a new identity columns, and refer to that when trying to increment the current tourid (which would be a little out of the ordinary), or create a "delete_requested" flag and update that rather than a physical delete - then have a purge routine to physically remove older delete requested rows (so long as it is not the current max(tourid) ) and change your query to add in a where clause : and isnull(delete_requested,'N') <> 'Y'  

The best solution is to rename that existing column (and index), add in a new column tourid as an identity, add back the primary key, change your pages accordingly. Only one other consideration and that would be any other dependant information using that ID. In which case, as a once off process, it is also possible to copy the table to a temp table, empty the real one and then set identity_insert tblTournament off and repopulate setting the new column with the old values, and then set identity_insert tblTournament on.

 

by: RickyGtzPosted on 2008-12-24 at 08:12:14ID: 23240634

Hi, Thank you all for all the proposed solution , I am modifying the delete  to  a "delete_requested" flag and updating that rather than a physical delete for now., If everithing as exoected I'' leave like that or if not I will create a temp table.. Thanks

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...