3

i tried something like this but the id value is not changing, getting the value for first record and set the value for all rest...

insert into table1 (Id,b,c,d) (select (select max(Id)+1 from table1),x,y,z from table2 where... ) 
4
  • Which database product are you using? SQL Server? Oracle? Something else? Commented Apr 29, 2010 at 16:33
  • 1
    im using mssql 2005 for this one. Commented Apr 29, 2010 at 16:36
  • 1
    You know this is not going to be concurrency-safe (w/o locking down table1), do you? Commented Apr 29, 2010 at 16:37
  • thats ok i wont use that command for concurrency works.. for example ill run this command once a day.. Commented Apr 29, 2010 at 16:39

1 Answer 1

6

Use an identity column. Then you can just do this:

INSERT INTO table1 (b, c, d) SELECT x, y, z FROM table2 WHERE ... 

If you don't want to use an auto-increment column you can get the same effect by using adding the row number of the row instead of always adding 1. This syntax works in almost all mainstream SQL databases (not MySQL though):

INSERT INTO table1 (Id, b, c, d) SELECT (SELECT MAX(Id) FROM table1) + ROW_NUMBER() OVER (ORDER BY x), x, y, z FROM table2 WHERE ... 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.