How to insert data into table while incrementing certain column

Zetsubo6996 21 Reputation points
2021-05-24T05:32:57.09+00:00

I would like to know is it possible to perform as per subject.
Example as per attachment.

From that table, I would like to insert the value as default but the 'Card_ID' column I would like the value to keep increment until a specific value.

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,492 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,707 questions
{count} votes

2 answers

Sort by: Most helpful
  1. EchoLiu-MSFT 14,621 Reputation points
    2021-05-24T08:52:37.163+00:00

    Hi @Zetsubo6996 ,

    Please try:

    ALTER TABLE tablename ADD id INT IDENTITY(1,1)  
      
    UPDATE t  
    SET Card_ID=CONCAT('BSH-CF',id)  
    FROM tablename t  
    

    The above code can make the Card_ID column increment to the last row in your table.

    If you have any question, please feel free to let me know.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.

    0 comments No comments

  2. Guoxiong 8,206 Reputation points
    2021-05-25T17:37:54.737+00:00

    If the Card_ID format is 'BSH-CFXXX' (XXX are the digits), try this:

    INSERT INTO YourTable
    SELECT TOP 1 
        Created_Date,
        Created_User,
        Updated_Date,
        Updated_User,
        Update_Frequency,
        LEFT(Card_ID, 6) + RIGHT('00' + CAST(CAST(RIGHT(Card_ID, 3) AS int) + 1 AS varchar(3)), 3),
        Card_Color,
        Category_ID,
        Person_ID,
        Active
    FROM YourTable
    ORDER BY Card_ID;
    
    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.