简体   繁体   English

SQL自动递增具有多个插入的值

[英]SQL Auto Increment a value with multiple inserts

We have a SQL query being executed against a SQL Server 2008 DB. 我们有一个针对SQL Server 2008数据库执行的SQL查询。

INSERT INTO ListDetail(ListID, Sequence, CompName, CompAddress, Date)
(
 SELECT
   12345 AS 'ListID',
   (MAX(ListDetail.Sequence) + 1) AUTO_INCREMENT as 'Sequence',
   Company.Name AS 'CompName',
   Company.Address AS 'CompAddress',
   GETDATE() AS 'Date'
 FROM Company
 WHERE CompanyType = 3
)

We want to find the max Sequence from ListDetail table.. and select records from the Company table into ListDetail. 我们要从ListDetail表中找到最大序列。然后从Company表中选择记录到ListDetail中。 But, we want to start with the next available Sequence value from ListDetail and then increment by 1 for each record inserted. 但是,我们要从ListDetail中的下一个可用Sequence值开始,然后为插入的每个记录加1。 The Sequence field in ListDetail is just a general INT field. ListDetail中的Sequence字段只是常规的INT字段。

We do not have control over the database its-self... so created a new table or altering the existing one is not an option. 我们无法控制数据库本身...因此无法创建新表或更改现有表。

One option would be to use Row_Number() with a subquery that returns the max() : 一种选择是将Row_Number()与返回max()的子查询一起使用:

Simplified solution: 简化解决方案:

insert into ListDetail 
select 12345, sq+row_number() over (order by (select null))
from company, (select max(sequence) sq from listdetail) t

INSERT INTO ListDetail(ListID, Sequence, CompName, CompAddress, Date)
SELECT
   12345,
   sq+row_number() over (order by (select null)),
   Name,
   Address,
   GETDATE()
FROM Company, (select max(sequence) sq from listdetail) t
WHERE CompanyType = 3

A simple approach like this should work for you. 这样的简单方法应该适合您。

INSERT INTO ListDetail(ListID, Sequence, CompName, CompAddress, Date)
(
 SELECT
 12345,
 (SELECT MAX(Sequence) + 1 FROM ListDetail),
 Company.Name,
 Company.Address,
 GETDATE()
 FROM Company
 WHERE CompanyType = 3
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM