复制同一张表中的行,并使用不同的ID列和另一列更新

时间:2018-09-07 15:32:57

标签: sql sql-server

我想复制表并将不同的值放在Type = B列和auto_increment id上 enter image description here

2 个答案:

答案 0 :(得分:0)

您可以使用插入选择来声明要插入的列,然后从同一表中选择相应的列,并为列类型分配文字'B'

insert into menu (  parent_id, order section, name, url, type)
select parent_id, order section, name, url, 'B'
from menu 
where type ='A'

答案 1 :(得分:0)

如果ID列是标识,则可以使用以下脚本实现:

insert into your_table ([parent_id], [order], [section], [name], [url], [type])
select [parent_id], [order], [section], [name], [url], 'B'
from your_table
where [type] = 'A' 

如果ID不是身份,请使用以下逻辑:

-- find current max
declare @max int = (select max(ID) from your_table)

-- declare table var
declare @table table ([Id] int identity(1,1), [parent_id] nvarchar(50), [order] int, [section] nvarchar(50), [name] nvarchar(50), [url] nvarchar(50), [type] nvarchar(50))

-- insert values into this table
insert into @table
select [parent_id], 
    [order], 
    [section], 
    [name], 
    [url], 
    'B'
from your_table
where [type] = 'A'

-- then insert values from teble variable to your table
insert into your_table ([Id],[parent_id], [order], [section], [name], [url], [type])
select @max + [Id],
    [parent_id], 
    [order], 
    [section], 
    [name], 
    [url], 
    [type]
from @table