SQL SERVER Insertar múltiples registros sin duplicar los que ya existen en la tabla

Samuel Isai Paredes Morales 21 Reputation points
2022-04-15T16:22:55.613+00:00

Buenas tardes, tengo que generar un script que pueda insertar más de 80 registros en una tabla, pero teniendo que validar que los que ya existan en la actual tabla, no los inserte e inserte solo los que no existen ahí.

La tabla tiene un id autoincrement, ese número no importa mucho porque la validación sería con un segundo campo llamado "co_code".

Saludos, espero que me puedan orientar.

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

2 answers

Sort by: Most helpful
  1. Naomi 7,361 Reputation points
    2022-04-15T17:20:49.527+00:00

    Try this syntax:

    insert into myTable (col1, col2, col3, etc., co_code)
    select col1, col2, col3, etc., co_code from (values (1, 2, .., 5), (....), (....)) v(col1, col2, col3, .., co_code)
    where not exists (select 1 from myTable t where t.co_code = v.co_code)

    0 comments No comments

  2. Bert Zhou-msft 3,421 Reputation points
    2022-04-18T01:57:57.637+00:00

    Hi,@Samuel Isai Paredes Morales

    Welcome to Microsoft T-SQL Q&A Forum!

    You can achieve it using merge into statement.

    MERGE INTO [TableA] AS [target]  
    using (SELECT distinct [Id] , [Selection1], [Selection2], [Selection3]  
           FROM   [TableB]  
        ) AS [source]  
    ON [target].[ID] = [source].ID  
    WHEN NOT matched THEN  
        INSERT ([Id], [Selection1], [Selection2], [Selection3])  
        VALUES ([Id], [Selection1], [Selection2], [Selection3]);   
    

    Refer to the link on this issue, if you want to know the use of merge into, please click here.
    Best regards,
    Bert Zhou


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. 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