1

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.

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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
)

2 Comments

I don't think this will produce the correct results (although I can see how it should make sense). Check out this fiddle: sqlfiddle.com/#!3/d8ed9/1
Agreed, it does seem to make sense, but I actually tried this at one point and it didn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.