Search code examples
sqlsql-serverstored-proceduresdatatablessql-insert

How to INSERT DATA from table to multiple tables with conditions


I need to insert data from source table to different tables by repsecting number of rows provided in a parameter table and without duplicates. The same ID's in the parameter table should be inserted in the destination tables for each range of rows. For example : FOR ID=1 insert first 200 rows in table_A then insert counting 300 lines starting from line 201 in source table .

ID FILENAME TOTAL_ROWS NUMBER_OF_ROWS_TO_INSERT DESTINATION_TABLE
1 FILENAME_X 500 200 TABLE_A
2 FILENAME_X 500 300 TABLE_B
3 FILENAME_Y 400 100 TABLE_C
4 FILENAME_Y 400 300 TABLE_D

Source table

s_id PHONE NAME
78 Cell 1 Cell 2
88 Cell 3 Cell 4

Destination tables TABLE A, B, C AND D (with same columns)

ID PHONE NAME
1 XXXX XXXX
2 XXXX XXXX
3 XXXX XXXX
4 XXXX XXXX
SELECT ROW_NUMBER() OVER(
       ORDER BY FILENAME) AS RowNum, ID,FILENAME,TOTAL_ROWS,NUMBER_OF_ROWS_TO_INSERT,DESTINATION_TABLE  
FROM [dbo].[parameter_table] ORDER BY FILENAME
OPEN cursor_files
    FETCH NEXT FROM cursor_files INTO @RowNum,@ID,@FILENAME,@TOTAL_ROWS,NUMBER_OF_ROWS_TO_INSERT,@NUMBER_OF_ROWS_TO_INSERT,@DESTINATION_TABLE

    WHILE @@FETCH_STATUS=0
    BEGIN
        IF @NUMBER_OF_ROWS_TO_INSERT > 0
do actions

END
        FETCH NEXT FROM cursor_files INTO @RowNum,@ID,@FILENAME,@TOTAL_ROWS,NUMBER_OF_ROWS_TO_INSERT,@NUMBER_OF_ROWS_TO_INSERT,@DESTINATION_TABLE

    END

    CLOSE cursor_files
    DEALLOCATE cursor_files
END


Solution

  • Using dynamic query:

     declare @strqry as nvarchar(max) = ''   
     
     ;with cte (id,destination_table, end_row) as (
     select id
        ,destination_table
        ,SUM (NUMBER_OF_ROWS_TO_INSERT) OVER (ORDER BY Id) as end_row  
      from ParameterTable )
    
      select @strqry = @strqry + 'insert into ' + destination_table + '(ID,Phone,Name) 
        select ' + str(ID) + ', phone, name 
        from SourceTable  
         where s_ID>' + str(isnull(Lag(end_row) OVER(ORDER BY id),0))  +' and s_ID<=' + str(end_row) +';' 
    
      from cte
    
       exec sp_executesql @strqry
    

    TEST

    http://sqlfiddle.com/#!18/0cea4c/1

    enter image description here