We have a SQL query being executed against a SQL Server 2008 DB.

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. But, we want to start with the next available Sequence value from ListDetail and then increment by 1 for each record inserted. The Sequence field in ListDetail is just a general INT field.

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():

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归因
不隶属于 StackOverflow
scroll top