使用条件将行从目标表复制到源表

时间:2014-05-22 19:14:24

标签: sql-server-2008

考虑以下两个表,

Parent Table
------------
Parentid
1
2
3
4
5
6


Child Table
-----------

Id  ParentId  Values
1     1        val1
2     2        val2
3     3        val3

现在我想将记录插入到parentid 4,5,6的子表中,所有值都来自Parentid 1,2,3。所以子表应该如下所示,

Id    ParentId   Values
 1       1         Val1
 2       2         Val2
 3       3         Val3
 4       4         Val1
 5       5         Val2
 6       6         Val3

请为我的方案分享SQL查询。我正在使用SQL Server 2008,所以请告诉我任何高级查询。

注意:在我的实际场景中,我有更多的记录。所以我不想在insert语句中硬编码任何值。

提前致谢!!

2 个答案:

答案 0 :(得分:0)

我希望你正在寻找像这样的东西

Declare @maxPID INT = (SELECT MAX(ParentId) from child)
DECLARE @count int= 1
DECLARE @pID INT

SET @pID = @maxPID

WHILE @count <= @maxPID
BEGIN
  SET @pID = @pID + 1
  INSERT INTO child
  Values (@pID, (SELECT TOP 1 Value from Child where parentId = @count))
  set @count = @count+1
END

这是sql小提琴http://sqlfiddle.com/#!3/7db5d/1

答案 1 :(得分:0)

DECLARE @Parent TABLE (pid INT);
DECLARE @Child TABLE (cid INT,pid INT, value varchar(50));

INSERT INTO @Parent 
VALUES  (1),
    (2),
    (3),
    (4),
    (5),
    (6)

INSERT INTO @Child
VALUES (1,1,'a'),
       (2,2,'b')


;WITH ChildValues AS
(
    SELECT value,
           ROW_NUMBER() OVER(ORDER BY RandonIDs ASC) RN
    FROM (
        SELECT RAND() RandonIDs,
               value
        FROM @Child 

        UNION ALL

        SELECT RAND(),
               value
        FROM @Child 

          )
)
,MissingParentIDs AS
(
    SELECT Pid,
           ROW_NUMBER() OVER(ORDER BY Pid ASC) RN   
    FROM @Parent P
    WHERE NOT EXISTS (SELECT C.Pid
              FROM @Child C
              WHERE C.Pid = P.Pid) 
)
SELECT Pid,
       Value
--INTO Destination Table
FROM MissingParentIDs M
INNER JOIN ChildValues V
ON M.RN = V.RN