How to add a row number to new table in SQL?
Asked Answered
K

4

8

I'm trying to create a new table using an existing table already using:

INSERT INTO NewTable (...,...)
   SELECT * from SampleTable

What I need to is add a record number at the beginning or the end, it really doesn't matter as long as it's there.

Sample Table

Elizabeth  RI 02914
Emily      MA 01834

Prospective New Table

1 Elizabeth  RI 02914
2 Emily      MA 01834

Is that at all possible?

This is what I ultimately I'm shooting for... except right now those tables aren't the same size because I need my ErrorTemporaryTable to have a column in which the first row has a number which increments by the previous one by one.

declare @counter int
declare @ClientMessage varchar(255)
declare @TestingMessage carchar(255)
select @counter = (select count(*) + 1 as counter from ErrorValidationTesting)
while @counter <= (select count(*) from ErrorValidationTable ET, ErrorValidationMessage EM where ET.Error = EM.Error_ID)
begin
    insert into ErrorValidationTesting (Validation_Error_ID, Program_ID, Displayed_ID, Client_Message, Testing_Message, Create_Date)
    select * from ErrorTemporaryTable

    select @counter = @counter + 1

end
Kolodgie answered 24/10, 2012 at 20:40 Comment(0)
D
10

You can use into clause with IDENTITY column:

SELECT IDENTITY(int, 1,1) AS ID_Num, col0, col1
INTO NewTable
FROM OldTable;

Here is more information

You can also create table with identity field:

create table NewTable
(
  id int IDENTITY,
  col0 varchar(30),
  col1 varchar(30)
)

and insert:

insert into NewTable (col0, col1)
SELECT col0, col1   
FROM OldTable;

or if you have NewTable and you want to add new column see this solution on SO.

Devil answered 24/10, 2012 at 20:43 Comment(2)
select into creates a new table. If the table already exists then it could be an issue.Renettarenew
Yes, I know, but I added one more solution how to create table correctly.Devil
P
10
INSERT INTO NewTable (...,...)
SELECT ROW_NUMBER() OVER (ORDER BY order_column), * from SampleTable
Perri answered 24/10, 2012 at 20:46 Comment(0)
R
2

If you are in SQL Server

INSERT INTO newTable (idCol, c1,c2,...cn)
SELECT ROW_NUMBER() OVER(ORDER BY c1), c1,c2,...cn
FROM oldTable
Renettarenew answered 24/10, 2012 at 20:47 Comment(0)
F
2

Try this query to insert 1,2,3... Replace MyTable and ID with your column names.

DECLARE @myVar int
SET @myVar = 0
UPDATE
  MyTable
SET
   ID =  @myvar ,
   @myvar = @myVar + 1
Faker answered 3/12, 2019 at 22:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.