将插入数据循环到多个表中

问题描述 投票:0回答:1

我有一个查询,我需要在其中进行手动插入

我可以做到,但是有很多记录,我一直在寻找是否可以建造一些东西。

我的结构有点像这样:

具有表的4个ID-主键值为:

var ids = "1,2,3,4";

loop over ids  {
    insert into table1(col1,col2,col3)  
    select col1,newid(),getdate() from table1 where id = ids - 1 at a time 

    var selectedID = get the id of the inserted row and then insert into anotehr table as: 

    insert into table2(col1,col2,col3,col4) 
    select selectedID, getdate(),getdate(),4 from table2 where fkID = ids - one at a time 
}
sql sql-server
1个回答
0
投票

您可以同时使用loopscursors,但通常可以避免使用它们。

您是否有特定原因要您一次插入一个?另一种方法是在临时表或CTE中暂存ID,例如

;WITH [Ids] AS
(
    SELECT '1' AS [ID]
    UNION 
    SELECT '2'
    UNION 
    SELECT '3'
    UNION 
    SELECT '4'
)
INSERT INTO [Table1]
(
    [Col1],
    [Col2],
    [Col3]
)
SELECT [Col1],
    NEWID(),
    GETDATE()
FROM [Table1] T
INNER JOIN [Ids] I ON I.[ID] = T.[Id];

这避免了任何循环,并且应表现得更好。

© www.soinside.com 2019 - 2024. All rights reserved.