sql-server-2008-r2primary-keytable-valued-parameters

Primary key duplicate in a table-valued parameter in stored procedure


I am using following code to insert date by Table Valued Parameter in my SP.

INSERT INTO banking.receivedcash
            (receivedcashid,
             date,
             time)
SELECT (SELECT Isnull(Max(receivedcashid), 0) + 1
        FROM   banking.receivedcash),
       t.date,
       t.time
FROM   @TVPCash AS t  

Actually it works when one record exists in my TVP but when it has more than one record it raises the following error :

'Violation of Primary key constraint 'PK_ReceivedCash''. Cannot insert duplicate key in object 'Banking.ReceivedCash'. The statement has been terminated.


Solution

  • Your query is indeed flawed if there is more than one row in @TVPCash. The query to retrieve the maximum ReceivedCashID is a constant, which is then used for each row in @TVPCash to insert into Banking.ReceivedCash.

    I strongly suggest finding alternatives rather than doing it this way. Multiple users might run this query and retrieve the same maximum. If you insist on keeping the query as it is, try running the following:

    insert into banking.receivedcash(
        ReceivedCashID,
        Date,
        Time
    )
    select 
        (select  isnull(Max(ReceivedCashID),0) from Banking.ReceivedCash)+
        ROW_NUMBER() OVER(ORDER BY t.Date,t.Time),
        t.Date,
        t.Time 
    from 
        @TVPCash as t
    

    This uses ROW_NUMBER to count the row number in @TVPCash and adds this to the maximum ReceivedCashID of Banking.ReceivedCash.