我有一个id(主键),name,value和branchId作为列的查找表。目前我有一组数据,其中branchId对于整个记录是相同的。我需要为name和value列复制具有相同值的数据,但在同一个表中使用不同的branchId值。
任何有关实现此目的的查询/脚本的帮助都将受到赞赏。
提前致谢!
答案 0 :(得分:1)
如果id
是IDENTITY
,则会自动生成其值:
INSERT INTO tableX --- the name of your table
(name, value, branchID)
SELECT
name, value, 23 --- branch to be added
FROM
tableX
WHERE
branchID = 12 ; --- the existing branch
对于一组branchID值,您可以CROSS
加入现有的表(或动态创建一个表):
INSERT INTO tableX
(name, value, branchID)
SELECT
t.name, t.value, ins.branchID
FROM
tableX AS t
CROSS JOIN
( VALUES
(1), (5), (7), (9), (10) --- branchIDs to be inserted
) AS ins (branchID)
WHERE
t.branchID = 12 ; --- the existing branchID
答案 1 :(得分:1)
insert into LookupTable
(
name,
value,
branchId
)
select
name,
value,
'BranchId2'
from LookupTable
where branchId = 'BranchId1'
答案 2 :(得分:0)
试试这个:
SELECT id, name, value, branchId,
row_number() over (partition by name, value order by id) new_branch_id
from tablename