插入新录音并更新外键

时间:2013-10-26 13:25:10

标签: tsql

我有这样的表

MainTable

 Id FolderName   Description      UserId
 1   Folder1     Description1       1
 2   Folder1     Description2       1
 3   Folder1     Desctiption3       1
 4   Folder2     Description1       2
 5   Folder2     Description2       2

ChildTable

 Id  FolderId     Title     UserId   imageName
 1      1          AA         1        AAA
 2      1          BB         1        BBB
 3      2          CC         1        CCC
 4      3          DD         1        DDD
 5      4          EE         2        EEE

我想在MainTable和ChildTable中选择所有记录对于userId = 1并再次将它们插入到MainTable / ChildTable中但UserId = 5,因此应更新新记录的FolderId,因此结果应如下所示:

Id FolderName   Description      UserId
 1   Folder1     Description1       1
 2   Folder1     Description2       1
 3   Folder1     Desctiption3       1
 4   Folder2     Description1       2
 5   Folder2     Description2       2
 6   Folder1     Description1       5
 7   Folder1     Description2       5
 8   Folder1     Desctiption3       5


 Id  FolderId     Title     UserId   imageName
 1      1          AA         1        AAA
 2      1          BB         1        BBB
 3      2          CC         1        CCC
 4      3          DD         1        DDD
 5      4          EE         2        EEE
 6      6          AA         5        AAA
 7      6          BB         5        BBB
 8      7          CC         5        CCC
 9      8          DD         5        DDD

我该怎么做? 谢谢

1 个答案:

答案 0 :(得分:0)

试试这个:

DECLARE @t table (OldFolderId int, NewFolderId int);

MERGE MainTable AS m
USING (SELECT Id, FolderName, Description
       FROM MainTable AS m
       WHERE UserId = 1) AS src
ON 1=2
WHEN NOT MATCHED THEN 
  INSERT (FolderName, Description, UserId)
  VALUES (src.FolderName, src.Description, 5)
OUTPUT src.Id AS OldFolderId, inserted.Id AS NewFolderId
INTO @t;

INSERT ChildTable (FolderId, Title, UserId, imageName)

SELECT t.NewFolderId, Title, 5, imageName
FROM ChildTable c
INNER JOIN @t t ON t.OldFolderId = c.FolderID
WHERE c.UserId = 1;

SQLFiddle here