Why SQL statement was run twice

Discussion in 'C#' started by arez, Feb 22, 2008.

  1. #1
    Hi All,
    I am a newbie in ASP, and I'm trying to fix a problem in an old system that I'm supporting.
    The problem is that sometimes, one particular insert statement is run twice,
    so I will have 2 duplicate records
    inserted. I have checked and made sure that
    the form is only submitted once.
    This problem does not happen all the time.
    And in the profiler, when it happened, I can see that the
    insert statement was run twice consecutively.

    Below is a snippet of the code:
    
    Dim strSQL, strID
    Dim objConnection, objRS
    Set objConnection = oGetADOConnection(strConnectionString) 	
    Dim strUserName 	
    
    Set objRS = objConnection.Execute("SELECT UserName FROM Member WHERE UserID = '" & userID & "')"
    		
    If Not objRS.EOF Then
    	wData = objRS.GetRows
    	strUserName = wData(0,0)
    End If	
    Set objRS = Nothing
    
    If strUserName <> "" Then	
                'this statement run twice			
    	strSQL = "IF NOT EXISTS " & _
    		  "(SELECT * from Card " & _
    		  "WHERE CardNo = '" & strCardNo & "' ) " & _
    		  "INSERT INTO Card (CardNo, UserName) " & _
    		  "VALUES("'" & strCardNo & "','" & strUserName & "')"  
    					
    	Set objRs = objConnection.Execute(strSQL)
    	Set objRs = Nothing
    			
    	strSQL = "SELECT @@IDENTITY as Value"
    	Set objRs = objConnection.Execute(strSQL) 
    					
    	wData = objRs.GetRows	
    			
    	strID = cstr(wData(0,0))
    		
    	Set objRs = Nothing	
    End If	
    Set objConnection = Nothing
    
    Code (markup):
    Does anyone know what cause this problem and how
    can I fix it?

    Thank you :)
     
    arez, Feb 22, 2008 IP
  2. plb

    plb Guest

    Messages:
    36
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    It needs to be done in a transaction to prevent a race condition.
     
    plb, Feb 22, 2008 IP
  3. arez

    arez Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Hi plb. Thank you for your reply.
    I'm not really sure what that means, but I'll check it out :D
     
    arez, Feb 24, 2008 IP