How to increment the row number and insert the new records into the table in sql

Naresh y 146 Reputation points
2023-06-16T17:00:13.86+00:00

HI I have the below query

Insert into Master(ID,NAME,Student)

select ID,Name,Value From Student

here ID is primary column ,

for every iteration i need to check the newly added value from ID column and insert that newly added record into my target table , if no new records are available, it will not insert any records into my target table

how do i implement this logic in sql server

please suggest your inputs here

thank you in advance

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,356 questions
SQL Server Integration Services
SQL Server Integration Services
A Microsoft platform for building enterprise-level data integration and data transformations solutions.
2,632 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 119.2K Reputation points
    2023-06-16T19:46:07.8033333+00:00

    For example:

    merge Master m using Student s on m.ID = s.ID
    when not matched then insert (ID, Name, Student) values (s.ID, s.Name, s.Value );
    
    0 comments No comments

  2. PercyTang-MSFT 12,506 Reputation points Microsoft Vendor
    2023-06-19T03:12:46.19+00:00

    Hi @Naresh y

    If I understand correctly, you can also try this.

    ;with CTE as(
      select ID,Name,Value from Student as A 
      where not exists(select ID from Master as B where A.ID = B.ID))
    insert into Master select ID,Name,Value From CTE;
    

    Best regards,

    Percy Tang


    If the answer is the right solution, please click "Accept Answer". If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    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.