Insert and update within same table

Brendan Hager 21 Reputation points
2021-05-22T13:59:44.777+00:00

Hello,

I need to copy rows within a table with specific types and dates, insert them back in to the same table, while updating the types and dates of the inserted rows.

Below is an example table.

98730-image.png

The rows highlighted in yellow are the existing rows, and the rows highlighted in blue should be the new rows.

Any help with the SQL is appreciated!

Developer technologies | Transact-SQL
SQL Server | Other
{count} votes

Accepted answer
  1. Erland Sommarskog 121.8K Reputation points MVP Volunteer Moderator
    2021-05-22T18:30:31.727+00:00
    INSERT Table1(Project, Type, Date)
       SELECT Project, 'B', dateadd(MONTH, 1, Date)
       FROM  Table1
    

    That's all I can make out from the information you have given.


1 additional answer

Sort by: Most helpful
  1. MelissaMa-MSFT 24,221 Reputation points
    2021-05-24T02:45:39.55+00:00

    Hi @Brendan Hager ,

    Welcome to Microsoft Q&A!

    Please also refer below example:

    drop table if exists Table1  
      
    create table Table1  
    (project int,  
    Type varchar(10),  
    Date date,  
    Col1 varchar(10),  
    Col2 decimal(8,2))  
      
    insert into Table1 values  
    (1,'A','05-01-2021','ABC',12.51),  
    (2,'A','05-01-2021','ABC',12.51),  
    (3,'A','05-01-2021','ABC',12.51)  
      
    insert into Table1   
    select project,'B',DATEADD(DD,1,date),col1,Col2 from Table1  
    where type='A'  
      
    select * from Table1  
    

    Output:

    project	Type	Date	Col1	Col2  
    1	A	2021-05-01	ABC	12.51  
    2	A	2021-05-01	ABC	12.51  
    3	A	2021-05-01	ABC	12.51  
    1	B	2021-05-02	ABC	12.51  
    2	B	2021-05-02	ABC	12.51  
    3	B	2021-05-02	ABC	12.51  
    

    If you would like to list all columns, you could refer below:

    SQL Server 2017 and later:

    select string_agg(COLUMN_NAME,',') from information_schema.columns where table_name = 'Table1'  
    

    SQL Server 2016 and earlier:

    select stuff(( select ','+ COLUMN_NAME from information_schema.columns where table_name = 'Table1'   
     FOR XML PATH('') ), 1, 1, '')   
    

    Output:

    project,Type,Date,Col1,Col2  
    

    Best regards,
    Melissa


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