Repeated inserts with Primary key, foreign key

前端 未结 2 1611
天涯浪人
天涯浪人 2021-01-22 13:14

Can anyone tell me how to do repeated multiple inserts on two tables with primary key, foreign key Here\'s what I\'ve done. This is a very snippet of what needs to be done.

相关标签:
2条回答
  • 2021-01-22 13:35

    Use the OUTPUT clause

     DECLARE @IDS TABLE (id INT) 
    
     INSERT INTO [dbo].[Table1]
                   ([UserID]  
                   ,[FirstName])
         OUTPUT inserted.id INTO @IDS          
         SELECT 'User1' AS [UserID]
                   ,'FirstName'
         FROM [dbo].[StatusTable]
    
         INSERT INTO [dbo].[Table2]
                    ([AccountID],[Status])
             SELECT Id, 'S' FROM @IDS
    
    0 讨论(0)
  • 2021-01-22 13:43

    Try a set based approach instead of this single row at a time logic. Load the first table, and then you can reference the first table and the data table in the insert to the second table, if you have something that makes each row unique.

    you can use a select statement instead of a value list:

    insert into table
    select rows from othertable (or multiple tables...it's a select statement as complicated as you wish)
    

    Pseudo coded:

    Insert into table2 (datacolumns)
    select table1.id, datacolumn 
    from statustable  s 
    inner join table1 t
    on (whatever makes these rows unique)
    
    0 讨论(0)
提交回复
热议问题