Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a SQL temp table with primary key and auto-incrementing field?

What am I missing here? I'm trying to get the ID field to be the primary key and auto increment so that I don't need to insert it explicitly.

CREATE TABLE #tmp ( ID INT IDENTITY(1, 1) , AssignedTo NVARCHAR(100), AltBusinessSeverity NVARCHAR(100), DefectCount int );  insert into #tmp  select 'user','high',5 union all select 'user','med',4   select * from #tmp 

I get an error with this saying:

Insert Error: Column name or number of supplied values does not match table definition.

like image 930
kacalapy Avatar asked Dec 07 '10 23:12

kacalapy


People also ask

Can a primary key be auto increment?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

How can create existing primary key column auto increment in SQL Server?

If you're looking to add auto increment to an existing table by changing an existing int column to IDENTITY , SQL Server will fight you. You'll have to either: Add a new column all together with new your auto-incremented primary key, or. Drop your old int column and then add a new IDENTITY right after.

Can temp table have primary key?

Only temporary tables can have additional non-clustered indexes defined. Table variables can only have primary keys defined at creation so this may be an important factor to consider when it comes to performance. The comments inline within the script define what the statements are testing.

How can insert auto increment value in SQL query?

To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function. For example, using Connector/ODBC you would execute two separate statements, the INSERT statement and the SELECT query to obtain the auto-increment value.


2 Answers

you dont insert into identity fields. You need to specify the field names and use the Values clause

insert into #tmp (AssignedTo, field2, field3) values (value, value, value) 

If you use do a insert into... select field field field it will insert the first field into that identity field and will bomb

like image 42
Devin Avatar answered Sep 16 '22 12:09

Devin


You are just missing the words "primary key" as far as I can see to meet your specified objective.

For your other columns it's best to explicitly define whether they should be NULL or NOT NULL though so you are not relying on the ANSI_NULL_DFLT_ON setting.

CREATE TABLE #tmp ( ID INT IDENTITY(1, 1) primary key , AssignedTo NVARCHAR(100), AltBusinessSeverity NVARCHAR(100), DefectCount int );  insert into #tmp  select 'user','high',5 union all select 'user','med',4   select * from #tmp 
like image 190
Martin Smith Avatar answered Sep 19 '22 12:09

Martin Smith