“Violation of PRIMARY KEY constraint 'PK_Vehicle_Transactions'. Cannot insert duplicate key in object 'dbo.Vehicle_Transactions”

后端 未结 1 481
时光取名叫无心
时光取名叫无心 2021-01-29 08:01

There\'s Webservice api that I design, Each time I push data cross the webservice this is what I get in return MOV = \"Violation of PRIMARY KEY constraint \'PK_Vehicle_Transacti

相关标签:
1条回答
  • 2021-01-29 08:30

    The exception already says it: Violation of PRIMARY KEY constraint 'PK_Vehicle_Transactions'. The table already contains a row with the Primary Key (TransactionID) given. A Primary Key is unique throughout the table.

    There are several solutions for your problem:

    1) Calculate the latest TransactionID

    VT = New Statn_Sync.DataSetTableAdapters.Vehicle_TransactionsTableAdapter().GetData()
    
    //Use query to select Max value of TransactionID (something like)
    Dim maxPK as Long =  'SELECT MAX(TransactionID) FROM dbo.Vehicle_Transactions'  
    
    //Increase the MaxPK with 1 to avoid duplicate key
     maxPK = maxPK + 1 
    
      For Each dr As DataRow In VT.Rows
       Dim iCount As Integer = 0
    
       //Use our variable in the insert
       Dim MOV As String = comT.insertVehicle_Transaction((maxPK  + iCount), _
                           Convert.ToDateTime(dr("Transaction_date")), _
    

    2) Use Auto Increment on TransactionID of dbo.Vehicle_Transactions

    For this i refer to the following post: Auto Increment .This post was made for the management studio of MSSQL 2012. But the same logic applies for earlier version (2008,2005)

    Other solutions might be found throughout StackOverflow

    If i can be of any further assistance, don't hesitate to give me sign!

    Note: If the previous data are of no use to you, you can always clear the table prior to the insert using the query: DELETE FROM dbo.Vehicle_Transactionsthis query removes all rows from the table. Though you have to wary for any Forgein Keys as they might cause dataloss/exceptions.

    0 讨论(0)
提交回复
热议问题