I have a database table that is created using the SELECT INTO SQL syntax. The database is in Access and consists of roughly 500,000 rows. The problem is when I do the join, the unique is the entire row - what I would like is an auto number ID field as the Primary Key.
Code I currently have is something like:
SELECT INTO new_table
FROM
(SELECT * FROM table a, table b WHERE a.name = b.name)
I was hoping there was a way to add a clause into my SELECT INTO query so I could add a primary key and create the table in one pass - is this possible?
If not, what is the best way to do this using SQL only?
SELECT INTO copies data from one table into a new table. SELECT INTO creates a new table located in the default filegroup.
If you would like to create a new table, the first step is to use the CREATE TABLE clause and the name of the new table (in our example: gamer ). Then, use the AS keyword and provide a SELECT statement that selects data for the new table.
The SELECT INTO command copies data from one table and inserts it into a new table. The following SQL statement creates a backup copy of Customers: SELECT * INTO CustomersBackup2017.
Adding a Primary Key
during a INSERT INTO
statement is not possible as far as I'm aware. What you can do however, is add an IDENTITY
column that auto increments by using SQL Server's IDENTITY()
function.
Something like this:
SELECT
ID = IDENTITY(INT, 1, 1),
col1,
col2
INTO new_table
FROM (SELECT * FROM table a, table b WHERE a.name = b.name)
In Access I don't believe that you can accomplish what you want in a single statement. What I think you'll need to do is...
Create the new table as you described in the question.
Add the AutoNumber column like this:
ALTER TABLE [new_table] ADD COLUMN [ID] AUTOINCREMENT NOT NULL
Make the column you just added the Primary Key:
ALTER TABLE [new_table] ADD CONSTRAINT NewTable_PK PRIMARY KEY (ID)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With