SQL Server Management Studio Express crashes when I try to run an ALTER TABLE query to add a PK with auto increment - sql-server-express

I have an existing table where I use existing column (type INT) as PK and manually increment its value with each row inserted. I wanted to change it to IDENTITY with auto increment. I found a thread here (http://stackoverflow.com/questions/4862385/sql-server-add-auto-increment-primary-key-to-existing-table) that seems to achieve exactly what I want. But every time I run the ALTER statement, Mgmt Studio crashes.
I had also tried to achieve my above goal by changing the column properties manually (Identity specification/Is Identity:yes) as in this thread (http://stackoverflow.com/questions/3876785/sql-server-cant-insert-null-into-primary-key-field). But every time I close the table after changing properties, I get an error
'Pix' table
Unable to modify table.
Cannot insert the value NULL into column 'picID', table 'photo.dbo.Tmp_Pix'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Not sure what's going on.

You cannot change an existing column to become an IDENTITY column.
What you need to do is:
create a new column with INT IDENTITY
drop the primary key constraint
drop the old column
add the primary key constraint on the new column
The trouble might be - if you already have data in that table - that the new identity values don't necessarily match the old values in your manual ID column.
If you need to preserve those, then it gets even more involved:
create a new table with the proper structure, and make sure that the ID column is INT IDENTITY
turn on IDENTITY_INSERT for that table
insert all the rows from the old table into the new one (and in the process, insert the old ID values into the new ID IDENTITY column)
turn off IDENTITY_INSERT for that table
drop the old table
possibly rename the new table

Related

add auto_increment to an existing db

I'm new to SQL. I created a table and filled it with some data. Now I want to change the properties of my primary key, so it will auto increment every single time by itself when adding data.
I know how to do it when creating a table, but where do I add auto_increment now, when I already have a created table with filled data?
Update
Try
ALTER TABLE [TableName] DROP COLUMN ID
ALTER TABLE [TableName] ADD ID INT IDENTITY(1,1)
If you had entered data to your table review this link that have an answer to you question SQL Server, How to set auto increment after creating a table without data loss?
You can't change logical structure column when you have some filled data in column. That's impossible. You must deleting data from column and use ALTER TABLE to change properites column

How to remove auto increment from table in sql server 2012

I have created a table in SQL Server 2012 with primary key as auto increment. But how can I remove that auto increment property from the table using a SQL query?
If you need to keep the data in that column then create a new column on the table which is of the same type (but a different name), copy the data from the column you want to get rid of to the new one, drop the old column and rename the new. Complete example:
CREATE TABLE test(col1 INT IDENTITY (1,1) NOT NULL, col2 VARCHAR(10) NULL);
ALTER TABLE test ADD col3 INT NULL;
UPDATE test SET col3 = col1;
ALTER TABLE test DROP COLUMN col1;
EXEC sp_rename 'dbo.test.col3', 'col1', 'COLUMN';
The easiest way would be:
Open SQL Server Management Studio.
Locate Server > DataBase > Table.
Right Click on the Table > Select Design.
In the design window, Highlight the column you want to modify.
In the Column Properties Window browse to Identity Specification > Is Identity And set to No.
Go to the toolbar menu > Table Designer > Select Generate Change Script...
Walla, you got the requested script.
I Like using this method for getting scripts, since it allows me to generate scripts I'm not sure how to compose from scratch and thus learning and improving my skills...
If it's a primary key column, then you have to drop the PK first. If there's any tables referencing it, then you'll have to drop these FKs to be able to drop the PK. After that, add another column of the same type, update it with values from identity column, drop the identity column, rename the new column to whatever the name of identity column was (with sp_rename procedure), recreate the PK, recreate the FKs, check if everything went right.
I'd be very careful doing it on a production database. Ensure that noone can access the data while you're doing this.
I searched a lot to find a simple solution to remove the auto increment because i should do a lot of work if i drop the column and the primary key which was a foreign key on another table where I should remove the data that are using my foreign ... finally I ended up with a very simple solution that made my life easy:
SET IDENTITY_INSERT <table_name> ON ;
SET IDENTITY_INSERT [TABLE] OFF .. this allows to remove the auto increment to off state.., so that we have to enter the value in thatcolumn

How to add identity to the column in SQL Server?

I have a table about 10 million rows. We just imported it from another database with SQL Server Management Studio. It creates table but without identity and primary key on primary key column.
I could add the primary key but couldn't add identity. It's all the time timing out when I'm doing it in designer. Even I set time out settings to 0.
I need to create probably another column set primary key and identity, copy data from old, delete old column and rename new one.
Can anyone show me what will be the best way to do it for such big tables, without additional overheating?
You cannot add IDENTITY to an existing column. It just cannot be done.
You'll need to create a new column of type INT IDENTITY and then drop the old column you don't need anymore (and possibly rename the new column to the old name - if that's needed)
Also: I would not do this in the visual designer - this will try to recreate the table with the new structure, copy over all data (all 10 millions rows), and then drop the old table.
It's much more efficient to use straight T-SQL statements - this will do an "in-place" update, non-destructive (no data is lost), and it doesn't need to copy around 10 millions rows in the process...
ALTER TABLE dbo.YourTable
ADD NewID INT IDENTITY(1,1) NOT NULL
When you add a new column of type INT IDENTITY to your table, then it will be automatically populated with consecutive numbers. You cannot stop this from happening, and you also cannot update the values later on.
Neither of those options is really very useful, in the end - you might end up with different ID values.... to do this right, you'd have to:
create the new table ahead of time, with the proper structure and the IDENTITY already in place
then turn on SET IDENTITY_INSERT (yourtable) ON on that table to allow values to be inserted into the identity column
copy over this data from the original source
turn off identity insert again: SET IDENTITY_INSERT (yourtable) OFF
Only with this approach will you be able to get the same ID's in an IDENTITY column in your new table.
Okay. I was able to add identity to the existing primary column with 10 million records. Took me about 30 mins.
The steps:
Change database to single user mode (to make sure no other connections to databse, can cause lock)
Open table in designer mode
Make change. Do not save
Click Generate Change Script button (usually on the left right above the Object Explorer)
Copy generated script
Close designer window (you can run only one instance at the time)
Open new window
Execute script
Done. Now your column has identity :)
You can add IDENTITY to an existing column. It just can be done.
in SSMS Just go to tools-->options-->Designers-->Table And Database Designers and uncheck option Prevent Saving changes that require table re-creation.
Now add identity in designer mode to the required column and save.
One way to set an identity column is during an insert with the option set identity_insert. For example, to change id in this table to identity:
create table YourTable (id int, value varchar(50))
You could use this script:
-- Create empty table as a copy of the original
select top 0 * into YourTable_New from YourTable
-- Drop the old ID column
alter table YourTable_New drop column id
-- Add a new ID column with identity
alter table YourTable_New add id int identity
-- Copy the old values into the identity column
set identity_insert YourTable_New on
insert YourTable_New (id, value) select id, value from YourTable
set identity_insert YourTable_New off
-- Drop the old table and rename the new one
drop table YourTable
exec sp_RENAME 'YourTable_New' , 'YourTable'

How to alter column from PRIMARY KEY to IDENTITY for Derby

The SQL for the creation of the table is:
CREATE TABLE myTable(id INTEGER NOT NULL PRIMARY KEY, ...)
Instead I need it to be:
CREATE TABLE myTable(id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), ...)
as described in the Derby documentation. So my question is what would be the alter statement I would need to create AFTER the initial create statement? In other words:
CREATE TABLE myTable(id INTEGER NOT NULL PRIMARY KEY, ...)
ALTER TABLE myTable ...
Thank you very much for the assistance!
Looking at the documentation this seems impossible. You can change the type length (not even the type itself), the default, nullability and the next generated value but even the last option requires the column to already be defined as IDENTITY. A thread from 2009 says that you can't even add an IDENTITY column. A test confirms this is true to this day.
So it seems there is only one solution: You have to replace the table. Something like this:
create a new table with a placeholder name that contains the desired columns
copy any data over from the original table
drop the original table
rename the new table
It's really an unfortunate solution because if you already have other tables referencing the id column of your table as that would mean further work.
I tried messing with the system tables but they seem to be read-only (and for good reason).
Looks like this issue in Derby has been fixed as of the 10.12.1.1 release. Now commands such as:
ALTER TABLE t ADD COLUMN x INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY
to an existing database now work, as does GENERATED BY DEFAULT. Looks like the change requires the underlying database to be at least in 10.11 format.
One technique is to: (a) create a new table with the new column defined as you desire, and all other columns as they were before, (b) run an INSERT INTO ... SELECT ... statement to copy all the data from the existing table to the new table, (c) RENAME TABLE to rename the old table to some other name, (d) RENAME TABLE to rename the new table to the correct tablename, and then finally (e) DROP TABLE the old table.

Is there a smart way to append a number to an PK identity column in a Relational database w/o total catastrophe?

It's far from the ideal situation, but I need to fix a database by appending the number "1" to the PK Identiy column which has FK relations to four other tables. I'm basically making a four digit number a five digit number. I need to maintain the relations. I could store the number in a var, do a Set query and append the 1, and do that for each table...
Is there a better way of doing this?
You say you are using an identity data type for your primary key so before you update the numbers you will have to SET IDENTITY_INSERT ON (documentation here) and then turn it off again after the update.
As long as you have cascading updates set for your relations the other tables should be updated automatically.
EDIT: As it's not possible to change an identity value I guess you have to export the data, set the new identity values (+10000) and then import your data again.
Anyone have a better suggestion...
Consider adding another field to the PK instead of extending the length of the PK field. Your new field will have to cascade to the related tables, like a field length increase would, but you get to retain your original PK values.
My suggestion is:
Stop writing to the tables.
Copy the tables to new tables with the new PK.
Rename the old tables to backup names.
Rename the new tables to the original table name.
Count the rows in all the tables and double check your work.
Continue using the tables.
Changing a PK after the fact is not fun.
If the column in question has an identity property on it, it gets complicated. This is more-or-less how I'd do it:
Back up your database.
Put it in single user mode. You don't need anybody mucking around whilst you do the surgery.
Execute the ALTER TABLE statements necessary to
disable the primary key constraint on the table in question
disable all triggers on the table in question
disable all foreign key constraints referencing the table in question.
Clone your table, giving it a new name and a column-for-column identical definitions. Don't bother with any triggers, indices, foreign keys or other constraints. Omit the identity property from the table's definition.
Create a new 'map' table that will map your old id values to the new value:
create table dbo.pk_map
(
old_id int not null primary key clustered ,
new_id int not null unique nonclustered ,
)
Populate the map table:
insert dbo.pk_map
select old_id = old.id ,
new_id = f( old.id ) // f(x) is the desired transform
from dbo.tableInQuestion old
Populate your new table, giving the primary key column the new value:
insert dbo.tableInQuestion_NEW
select id = map.id ,
...
from dbo.tableInQuestion old
join dbo.pk_map map on map.old_id = old.id
Truncate the original table: TRUNCATE dbo.tableInQuestion. This should work—safely—since you've disabled all the triggers and foreign key constraints.
Execute SET IDENTITY_INSERT dbo.tableInQuestion ON.
Reload the original table:
insert dbo.tableInQuestion
select *
from dbo.tableInQuestion_NEW
Execute SET IDENTITY_INSERT dbo.tableInQuestion OFF
Execute drop table dbo.tableInQuestion_NEW. We're all done with it.
Execute DBCC CHECKIDENT( dbo.tableInQuestion , reseed ) to get the identity counter back in sync with the data in the table.
Now, use the map table to propagate the changed primary key column down the line. Depending on your E-R model, this can get complicated as foreign keys referencing the updated column may themselves be part of a composite primary key.
When you're all done, start re-enabling the constraints and triggers you disabled. Make sure you do this using the WITH CHECK option. Fix any problems thus uncovered.
Finally, drop the map table, and clear the single user flag and bring your system(s) back online.
Piece of cake! (or something.)
Consider this approach:
Reset the identity seed to the 10000 + the current seed.
Set identity insert on
Insert into the table from the values in the table and add 10000 to the identity column on the way.
EX:
Set identity insert on
Insert Table(identity, column1, eolumn2)
select identity + 10000, column1, column2
From Table
Where identity < origional max identity value
After the insert you know the identity is exactly 10000 more than the origional.
Update the foreign keys by addding 10000.