SQL Server 如何使用条件将表中的DATA插入到多个表中

hkmswyz6  于 2022-12-26  发布在  其他
关注(0)|答案(1)|浏览(118)

我需要将数据从源表插入到不同的表中,方法是重新划分参数表中提供的行数,并且不重复。参数表中的相同ID应插入到目标表中的每个行范围中。例如:FOR ID = 1在table_A中插入前200行,然后在源表中从第201行开始插入300行。
| 识别号|文件名|总计_行|要插入的行数|目的地_表格|
| - ------| - ------| - ------| - ------| - ------|
| 1个|文件名_X|五百|二百|表_A|
| 第二章|文件名_X|五百|三百|表_B|
| 三个|文件名_Y|四百|一百|表C|
| 四个|文件名_Y|四百|三百|表D|

    • 源表**

| s_标识符|电话|姓名|
| - ------| - ------| - ------|
| 七十八|细胞1|单元2|
| 八十八|单元格3|单元4|

    • 目标表格**表格A、B、C和D(具有相同的列)

| 识别号|电话|姓名|
| - ------| - ------| - ------|
| 1个|XXXX年|XXXX年|
| 第二章|XXXX年|XXXX年|
| 三个|XXXX年|XXXX年|
| 四个|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
t40tm48m

t40tm48m1#

使用动态查询:

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

测试

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

相关问题