根据其他列复制同一表中的数据

时间:2017-10-31 21:22:56

标签: sql-server tsql

我有一个名为tableX的表,就像这样。注意childNo和parentNo列的关系。

childNo | parentNo |locationId |value
--------+----------+-----------+--------+
26      |    NULL  |   7       | value1 |
27      |    NULL  |   7       | value2 |
28      |    27    |   7       | value3 |
29      |    27    |   7       | value4 |
30      |    27    |   7       | value5 |
34      |    NULL  |   7       | value6 |

我想用新的childNo和parentNo(保护关系)将相同的值列信息复制到另一个locationId(比如说locationId = 3)

预期产出。

childNo | parentNo |locationId |value
--------+----------+-----------+--------+
36      |    NULL  |   3       | value1 |
37      |    NULL  |   3       | value2 |
38      |    37    |   3       | value3 |
39      |    37    |   3       | value4 |
40      |    37    |   3       | value5 |
44      |    NULL  |   3       | value6 |

如何使用T-SQL实现这一目标?

2 个答案:

答案 0 :(得分:0)

也许我错过了什么,但你可以做到:

insert into t(childNo, parentNo, locationId, value)
    select t.childNo + 10, t.ParentNo + 10, 3, t.value
    from t
    where t.locationId = 7;

答案 1 :(得分:0)

我在SQL Server 2012中尝试此示例。

DECLARE @lastParent int;
DECLARE @lastChild int;
DECLARE @newLocationId int;

SET @newLocationId = 3;
SELECT @lastParent = MAX(ParentNo) FROM tableX WHERE ParentNo IS NOT NULL;
SELECT @lastChild = MAX(ChildNo) from tableX;

INSERT INTO tableX (childNo, parentNo , LocationId, valueColumn)
SELECT
    @lastChild + ROW_NUMBER() OVER (PARTITION BY LocationId ORDER BY childNo) AS childNo,
    CASE WHEN (ParentNo IS NOT NULL) then @lastParent + 1 
         ELSE ParentNo
         END as NewParentNo,
    @NewLocationId as NewLocationId, valueColumn 
FROM tableX 
WHERE LocationId = 7
ORDER BY childNo

此代码的两个实例同时运行,可以生成重复值。我认为你的表必须对childNo有唯一约束,有些触发器验证parentNo