Primary key column auto increment in existing table

John Kelly 166 Reputation points
2021-08-10T15:07:33.007+00:00

Hi

I have a Stored procedure (part shown) with the following:

DECLARE @Orders table (CompanyCode CHAR(3),OrderNumber int)
INSERT INTO @Orders(CompanyCode,OrderNumber)

At the end of the SP i have the following that i have commented out while testing:

--INSERT INTO hrsoplog (comp_id,u_version,order_no,print_dt,print_by,print_type)
--SELECT
-- CompanyCode,
-- '!',
-- OrderNumber,
-- GETDATE(),
-- 'AUTO',
-- 'Order'
--FROM @Orders

hrsoplog is an existing table and has a Primary Key called print_id

How do i start this print_id at 1 and increment by 1 everytime a new row is added.

Thanks in advance

John

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,632 questions
{count} votes

Accepted answer
  1. Erland Sommarskog 110.6K Reputation points MVP
    2021-08-10T22:00:18+00:00

    It is not clear if print_id has the IDENTITY property. In that case, you need to do nothing at all.

    If not, you can do:

    BEGIN TRANSACTION
    
    SELECT @id = isnull(MAX(print_id, 0) FROM hrsoplog WITH (UPDLOCK)
    
    INSERT INTO hrsoplog (print_id, comp_id,u_version,order_no,print_dt,print_by,print_type)
    SELECT row_number() OVER(ORDER BY (SELECT 1)) + @id, 
     CompanyCode,
     '!',
     OrderNumber,
     GETDATE(),
     'AUTO',
     'Order'
    FROM @Orders
    
    COMMIT TRANSACTION
    
    0 comments No comments

6 additional answers

Sort by: Most helpful
  1. Olaf Helper 44,341 Reputation points
    2021-08-16T13:04:19.147+00:00

    SELECT @id = isnull(MAX(print_id, 0) FROM hrsoplog WITH (UPDLOCK)

    The closing brace for the MAX function is missing =>

    SELECT @id = isnull(MAX(print_id), 0) FROM hrsoplog WITH (UPDLOCK)
    
    0 comments No comments

  2. John Kelly 166 Reputation points
    2021-08-17T18:46:03.247+00:00

    Many thanks to everyone who helped with this. A great resource to use.

    I tried the solution put forward by Erland and it works perfect.

    124063-image.png

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.