Can you add identity to existing column in sql server 2008? - sql-server

In all my searching I see that you essentially have to copy the existing table to a new table to chance to identity column for pre-2008, does this apply to 2008 also?
thanks.
most concise solution I have found so far:
CREATE TABLE Test
(
id int identity(1,1),
somecolumn varchar(10)
);
INSERT INTO Test VALUES ('Hello');
INSERT INTO Test VALUES ('World');
-- copy the table. use same schema, but no identity
CREATE TABLE Test2
(
id int NOT NULL,
somecolumn varchar(10)
);
ALTER TABLE Test SWITCH TO Test2;
-- drop the original (now empty) table
DROP TABLE Test;
-- rename new table to old table's name
EXEC sp_rename 'Test2','Test';
-- see same records
SELECT * FROM Test;

we cannot add identity to an existing column using sql command but we can do it using GUI.
Right click on the table - design - select the column on which you want to add identity.
go to the properties available below. find the identity specification and set it to yes.
save the table.
if it is not saved the go to tools from the menu - options - table designer - uncheck the checkbox prevent saving changes. now you can save the table modifications.
now your existing table had identity.

In all of the new feature documents I read about 2008, adding identity to an existing column was not a feature I recall. The solution you've found is correct and I think the process of adding identity increment to a column automatically would be only rarely useful.

Well you can do something like this.
ALTER TABLE my_table ADD ID_COLUMN INT IDENTITY (1,1) NOT NULL

You can add the IDENTITY property to an existing column using the GUI of Enterprise Manager / Management Studio.

In SQL 2005 and earlier, you could not modify an existing column to become an identity column. I deem it very very unlikely that MS changed that in 2008.

Related

How to add one column into existing SQL Table

I have a SQL Server table and it is located on a remote server. I can connect to it with SQL Server Management Studio but opening it takes time instead, I am doing my jobs with SQL Query window without reaching it.
Recently I've made a change on the local copy of this table and want to update the remote one as well. All I've done is adding one more column which is Nullable and I'd like to learn how to add this one more column to the remote SQL Server with T-SQL without ruining the remote one data.
Here is the additional info:
Table Name: Products
Columns to be added: LastUpdate, Nullable and varchar(200)
Thanks.
The syntax you need is
ALTER TABLE Products ADD LastUpdate varchar(200) NULL
This is a metadata only operation
What about something like:
Alter Table Products
Add LastUpdate varchar(200) null
Do you need something more complex than this?
Its work perfectly
ALTER TABLE `products` ADD `LastUpdate` varchar(200) NULL;
But if you want more precise in table then you can try AFTER.
ALTER TABLE `products` ADD `LastUpdate` varchar(200) NULL AFTER `column_name`;
It will add LastUpdate column after specified column name (column_name).
alter table table_name add field_name (size);
alter table arnicsc add place number(10);

any idea why running alter column causes column to go from “not null” to “null”?

I am mass updating a SQL Server database. I am changing all our numeric(38,0) columns to int (yes, SQL Server scripts were created from Oracle scripts).
Using SMO and C# (I am a sw engineer), I managed to generate really nice scripts like SQL Server Management Studio would.
It all works very nicely except for one particular issue:
For a handful of tables, when I call
ALTER TABLE [myTable] ALTER COLUMN [columnA] INT
it decides to also change the column from NOT NULL to NULL. That, of course is a huge issue since I need to regenerate primary keys for most of those tables on those particular columns.
Obviously, I have plenty of options using SMO to find out which columns are primary keys and force them to be NOT NULL after or while I am updating the data type, but I am really curious as to what can be causing this.
Regards,
Eric.
Because in the absense of NOT NULL, the default is NULL.
ALTER TABLE [myTable]
ALTER COLUMN [columnA] INT NOT NULL
from ALTER TABLE (Transact-SQL)
When you create or alter a table with
the CREATE TABLE or ALTER TABLE
statements, the database and session
settings influence and possibly
override the nullability of the data
type that is used in a column
definition. We recommend that you
always explicitly define a column as
NULL or NOT NULL for noncomputed
columns.

How to remove identity column from table

I have created a table with employee id as identity column. Now, I want to remove identity and replace datatype as bigint. I am using Sql Compact edition. How to achieve this?
I don't believe you can, using TSQL, remove the IDENTITY property from a column.
Instead:
Add a new BIGINT column to the table
Copy the data from the current IDENTITY field into the new field
Drop the existing column
Rename the new column to the correct name
You can do it in SSMS in the Design view for the table. I believe behind the scenes it does something like above.
Update:
To confirm, in SSMS 2K8 when you try to remove the IDENTITY property from a column and then save it, it will actually recreate the table (you can see what it does exactly by monitoring in SQL Profiler). In order to do it in SSMS, you need to ensure you have the "Prevent saving changes that require table re-creation" option turned OFF in Tools-> Options -> Designers -> Table and Database Designers. I think it defaults to ON, which would result in an error message when you try to do it otherwise.
In "real" SQL Server, you'd have to do these steps - not sure if SQL Server CE allows the same, but give it a try! I'm assuming you probably have your PRIMARY KEY constraint on that column, too - right? If not, you don't need to do the first and last step. And I'm assuming you want to have the IDENTITY on the column again, right?
-- DROP the primary key constraint (if you have that on your column)
ALTER TABLE dbo.Employees
DROP CONSTRAINT PK__Employees__3214EC274222D4EF
-- ALTER the datatype into BIGINT
ALTER TABLE dbo.Employees
ALTER COLUMN Employee_ID BIGINT
-- set PK constraint again
ALTER TABLE dbo.Employees
ADD CONSTRAINT PK_Employees PRIMARY KEY(Employee_ID)
This should help - http://www.sqlmag.com/Files/23/22081/Listing_03.txt

How do I add the identity property to an existing column in SQL Server

In SQL Server (in my case, 2005) how can I add the identity property to an existing table column using T-SQL?
Something like:
alter table tblFoo
alter column bar identity(1,1)
I don't beleive you can do that. Your best bet is to create a new identity column and copy the data over using an identity insert command (if you indeed want to keep the old values).
Here is a decent article describing the process in detail:
http://www.mssqltips.com/tip.asp?tip=1397
The solution posted by Vikash doesn't work; it produces an "Incorrect syntax" error in SQL Management Studio (2005, as the OP specified). The fact that the "Compact Edition" of SQL Server supports this kind of operation is just a shortcut, because the real process is more like what Robert & JohnFX said--creating a duplicate table, populating the data, renaming the original & new tables appropriately.
If you want to keep the values that already exist in the field that needs to be an identity, you could do something like this:
CREATE TABLE tname2 (etc.)
INSERT INTO tname2 FROM tname1
DROP TABLE tname1
CREATE TABLE tname1 (with IDENTITY specified)
SET IDENTITY_INSERT tname1 ON
INSERT INTO tname1 FROM tname2
SET IDENTITY_INSERT tname1 OFF
DROP tname2
Of course, dropping and re-creating a table (tname1) that is used by live code is NOT recommended! :)
Is the table populated? If not drop and recreate the table.
If it is populated what values already exist in the column? If they are values you don't want to keep.
Create a new table as you desire it, load the records from your old table into your new talbe and let the database populate the identity column as normal. Rename your original table and rename the new one to the correct name :).
Finally if the column you wish to make identity currently contains primary key values and is being referenced already by other tables you will need to totally re think if you're sure this is what you want to do :)
There is no direct way of doing this except:
A) through SQL i.e.:
-- make sure you have the correct CREATE TABLE script ready with IDENTITY
SELECT * INTO abcTable_copy FROM abcTable
DROP TABLE abcTable
CREATE TABLE abcTable -- this time with the IDENTITY column
SET IDENTITY_INSERT abcTable ON
INSERT INTO abcTable (..specify all columns!) FROM (..specify all columns!) abcTable_copy
SET INDENTITY_INSERT abcTable OFF
DROP TABLE abcTable_copy
-- I would suggest to verify the contents of both tables
-- before dropping the copy table
B) Through MSSMS which will do exactly the same in the background but will less fat-fingering.
In the MSSMS Object Explorer right click the table you need to modify
Select "design" Select the column you'd like to add IDENTITY to
Change the identity setting from NO -> YES (possibly seed)
Ctr+S the table
This will drop and recreate the table with all original data in it.
If you get a warning:
Go to MSSMS Tools -> Options -> Designers -> Table and database Designers
and uncheck the option "Prevent saving changes that require table re-creation"
Things to be careful about:
your DB has enough disk space before you do this
the DB is not in use (especially the table you are changing)
make sure to backup your DB before doing it
if the table has a lot of data (over 1G) try it somewhere else first
before using in real DB
Create a New Table
SELECT * INTO Table_New FROM Table_Current WHERE 1 = 0;
Drop Column from New Table
Alter table Table_New drop column id;
Add column with identity
Alter table Table_New add id int primary key identity;
Get All Data in New Table
SET IDENTITY_INSERT Table_New ON;
INSERT INTO Table_New (id, Name,CreatedDate,Modified)
SELECT id, Name,CreatedDate,Modified FROM Table_Current;
SET IDENTITY_INSERT Table_New OFF;
Drop old Table
drop table Table_Current;
Rename New Table as old One
EXEC sp_rename 'Table_New', 'Table_Current';
alter table tablename
alter column columnname
add Identity(100,1)

SQL Server how to drop identity from a column

Is there an easy way to remove an identity from a table in SQL Server 2005?
When I use Management Studio, it generates a script that creates a mirror table without the identity, copies the data, drops the table, then renames the mirror table, etc. This script has 5231 lines in it because this table/column have many FK relations.
I'd feel much more comfortable running a simple alter/drop. Any ideas?
EDIT
I think I'm just going to go with the 5,231 line script from Enterprise Manager. However, I'm going to break it up into smaller parts which I can run and control better. This table "behaves" strange, if you try to delete 1 row (even one you just inserted, which is not in any other FK table), you get this error:
delete MyTable where MyPrimaryKey=1234
Msg 8621, Level 17, State 2, Line 1
The query processor ran out of stack space during query optimization. Please simplify the query.
No doubt, all the FKs. We will halt all access to our application and run in single user mode when we make these schema and related application changes. However, we need this to run fast, and I need an idea of how long it will take. I guess that I'll just have to test, test, test.
If you are on SQL Server 2005 or later, you can do this as a simple metadata change (NB: doesn't require an edition supporting partitioning as I originally stated).
Example code pilfered shamelessly from the workaround by Paul White on this Microsoft Connect Item.
USE tempdb;
GO
-- A table with an identity column
CREATE TABLE dbo.Source
(row_id INTEGER IDENTITY PRIMARY KEY NOT NULL, data SQL_VARIANT NULL);
GO
-- Some sample data
INSERT dbo.Source (data)
VALUES (CONVERT(SQL_VARIANT, 4)),
(CONVERT(SQL_VARIANT, 'X')),
(CONVERT(SQL_VARIANT, {d '2009-11-07'})),
(CONVERT(SQL_VARIANT, N'áéíóú'));
GO
-- Remove the identity property
BEGIN TRY;
-- All or nothing
BEGIN TRANSACTION;
-- A table with the same structure as the one with the identity column,
-- but without the identity property
CREATE TABLE dbo.Destination
(row_id INTEGER PRIMARY KEY NOT NULL, data SQL_VARIANT NULL);
-- Metadata switch
ALTER TABLE dbo.Source SWITCH TO dbo.Destination;
-- Drop the old object, which now contains no data
DROP TABLE dbo.Source;
-- Rename the new object to make it look like the old one
EXECUTE sp_rename N'dbo.Destination', N'Source', 'OBJECT';
-- Success
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
-- Bugger!
IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
PRINT ERROR_MESSAGE();
END CATCH;
GO
-- Test the the identity property has indeed gone
INSERT dbo.Source (row_id, data)
VALUES (5, CONVERT(SQL_VARIANT, N'This works!'))
SELECT row_id,
data
FROM dbo.Source;
GO
-- Tidy up
DROP TABLE dbo.Source;
I don't believe you can directly drop the IDENTITY part of the column. Your best bet is probably to:
add another non-identity column to the table
copy the identity values to that column
drop the original identity column
rename the new column to replace the original column
If the identity column is part of a key or other constraint, you will need to drop those constraints and re-create them after the above operations are complete.
You could add a column to the table that is not an identity column, copy the data, drop the original column, and rename the new column to the old column and recreate the indexes.
Here is a link that shows an example. Still not a simple alter, but it is certainly better than 5231 lines.

Resources