Sql server SQL Server insert语句自动递增

Sql server SQL Server insert语句自动递增,sql-server,Sql Server,我有一个SQL insert语句,如下所示: insert into mytable(ID,Keyindex,KeyValue) select Id,1,GenreID from mytable2 这将使用以下数据填充我的表: id GenreID ColumnB 0006342c-47bc-436a-a23a-3b40360d9a30 16 1 0006342c-47bc-436a-a23a-3

我有一个SQL insert语句,如下所示:

insert into mytable(ID,Keyindex,KeyValue) 
select Id,1,GenreID 
from mytable2
这将使用以下数据填充我的表:

id                                      GenreID  ColumnB
0006342c-47bc-436a-a23a-3b40360d9a30    16       1
0006342c-47bc-436a-a23a-3b40360d9a30    19       1
00109775-f0f8-463e-8134-f842aac8b5df    12       1
001211e3-9bf8-45ad-8297-7a0a94aaf06e    13       1
0025218a-9624-4f5e-86cc-f1cfe862cd2a    16       1 
0025218a-9624-4f5e-86cc-f1cfe862cd2a    11       1
0025218a-9624-4f5e-86cc-f1cfe862cd2a    15       1
问题是ID、GenreId和ColumnB是主键,我目前正在插入一个常量值“1”,这会导致主键冲突

如何插入到表中,以便在ID相同的情况下,用增量值填充ColumnB

例如:

id                                      GenreID  ColumnB
0006342c-47bc-436a-a23a-3b40360d9a30    16       1 
0006342c-47bc-436a-a23a-3b40360d9a30    19       2 
00109775-f0f8-463e-8134-f842aac8b5df    12       1
001211e3-9bf8-45ad-8297-7a0a94aaf06e    13       1
0025218a-9624-4f5e-86cc-f1cfe862cd2a    16       1
0025218a-9624-4f5e-86cc-f1cfe862cd2a    16       2
0025218a-9624-4f5e-86cc-f1cfe862cd2a    16       3

肮脏的黑客行为是使用
id-someNumber
id+someNumber
而不仅仅是
1

如果这是一次“失火忘记”操作,可以接受什么


如果您必须检查唯一性,则触发器可以作为解决方案。

您可以尝试启用重复选项:

insert into mytable(ID,Keyindex,KeyValue) 
select Id,1,GenreID 
from mytable2
ON DUPLICATE KEY UPDATE Keyindex = Keyindex+1;

你的问题有点让人困惑。在“示例”部分中,它看起来像
0025218a-9624-4f5e-86cc-f1cfe862cd2a
的genreID应该是
16,17,19
,而不是
16,16,16

不过,假设我理解您的意思是正确的,您可以在上使用按id分区的
行编号()

insert into mytable(ID,Keyindex,KeyValue) 
select   id, GenreID , ROW_NUMBER() OVER (Partition by id order by id) as ColumnB
from     mytable2
order by id, 
         genereid

注意:您没有指定版本,但这将在sql 2005+

中起作用。第一部分中的列名与第二部分中显示的列名不同步。因此,如果GenreID和ColumnB的组合不唯一,您只希望ColumnB递增?听起来你需要一个触发器。注意这是未经测试的。只是想一想。根据需要修改。如果您不使用MySQL,请查看以下链接:Msg 156,级别15,状态1,第2行关键字“ON”附近的语法不正确。ON-replice语法对SQL server不起作用。你需要一个插入前触发器。