March 6, 2009 at 9:35 am
Hi- I have a Dought.
I have 2 tables, they are:
Table 1 with 2 fields and Table 2 that has 3 fields.
Table 1 has this 2 fields:
Name and address.
Table 2 has this 3 fields:
Number , Name and address.
This table 1 has 20000 records (for example) and I need to put this records (insert ) into table 2.
Two of the fields in this two tables are exactly of the same type and name.
But table 2 has one more field (that is not an identity, and it will not became one identity field) , that is numeric (int).
Table 2 has already same records and I need to insert now , all the data from table 1 to table 2.
Suppose my table 2 data is this:
1 Paul Street1
2 Marc Street2
How can I insert (code sample) the data of table1 into table 2 and the field of type number of table 2 is incremented in 1 every time a new record is placed on table2 ?
I only know how to do this by using cursors, but that’s not good.
Can someone help me please?
In this case , the first record to be insert into table2 would be inserted with the number 3.
Tks,
Pedro
March 6, 2009 at 9:39 am
INSERT INTO Table2 (Number, Name, Address)
SELECT ROW_NUMBER() OVER(ORDER BY Name, Address) AS counter,
Name, Address
FROM Table1
-- Gianluca Sartori
March 6, 2009 at 9:43 am
tks old hand for reply so quick.
i will trie and will report to you the result
will this code start the counter from number 3? since number 1 and number 2 are already in the table 2?
March 6, 2009 at 9:57 am
This will insert based on the result set, which will start from 1.
Also, please note your name and the poster's name are in the same position relative to the post. "Old Hand" is a level or title given based on posts. The poster's name is above that, in bold.
March 6, 2009 at 10:04 am
I'm sorry, I didn't see you needed to start from 3.
INSERT INTO Table2 (Number, Name, Address)
SELECT ROW_NUMBER() OVER(ORDER BY Name, Address) + 2 AS counter,
Name, Address
FROM Table1
Sorry also for not putting my name in the reply.
I have such a few time to dedicate to SSC that sometimes I tend to be too concise.
Regards
Gianluca
-- Gianluca Sartori
March 6, 2009 at 10:10 am
tks once again for help.
But in this case i think you did not understud my question , i don't need to always start from 3.
I need to start from the last number in table 2 , in this case is 3, but it could be 10.
tks, again,
Pedro
March 9, 2009 at 1:49 am
Ok, so I guess you need something like this:
INSERT INTO Table2 (Number, Name, Address)
SELECT ROW_NUMBER() OVER(ORDER BY Name, Address) + (SELECT MAX(Number) FROM Table2) AS counter,
Name, Address
FROM Table1
-- Gianluca Sartori
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply