SQL Auto使用多个插入增加值

时间:2014-04-01 21:39:06

标签: sql insert sequence auto-increment insert-into

我们正在针对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
)

我们希望从ListDetail表中找到最大序列..并从Company表中选择记录到ListDetail。但是,我们希望从ListDetail中的下一个可用Sequence值开始,然后为每个插入的记录递增1。 ListDetail中的Sequence字段只是一个通用的INT字段。

我们无法控制数据库...因此创建新表或更改现有表不是一种选择。

2 个答案:

答案 0 :(得分:1)

一种选择是将Row_Number()与返回max()的子查询一起使用:

简化解决方案:

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

答案 1 :(得分:0)

这样一个简单的方法对你有用。

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
)