使用循环或数组将数据从一个表插入到另一个sql

时间:2018-10-16 06:55:31

标签: sql-server

我试图将数据从一个表插入到另一个表(从表[PPRS]到表[Verify]),其中PPRS中的标题与表[Master]中的标题相同。有人建议我使用循环或数组来插入数据,而不是对其进行硬编码,因此我先尝试了循环

这是我的代码:

Declare @counter int 
declare @total int
set @counter = 0
SELECT @total =  Count(*) FROM PPRS

while @counter <= @total
    begin 
        set @counter += 1
        insert into [Verify]
        select [Task_ID],
        [Project_StartDate] ,
        [PPR_Caption],
        [Date] 
        FROM PPRS
        where [PPR_Caption] in (SELECT [Caption] from MasterRecords)

    end 

无论怎么说(插入0行)

样本数据: Task_ID PPR_Caption Project_StartDate用户 17288 WC-青年环境服务(12/15)30/09/2018 Grace Modubu

1 个答案:

答案 0 :(得分:1)

这将插入来自PPRS的所有记录,其中字幕位于MasterRecords中。无需循环

insert into [Verify] 
select [Task_ID], [Project_StartDate] , [PPR_Caption], [Date] 
FROM PPRS 
where [PPR_Caption] in (SELECT [Caption] from MasterRecords);