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.
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.
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.
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.
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.
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
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
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