Monday, March 12, 2012

How to add IDENTITY to existing column

Hi All
Is it possible to alter an EXISTING column to make it an IDENTITY seed
column using T-SQL. I've looked at the BOL help for alter table/column but
can't seem to decipher how it should be done. It can be easily done using
enterprise manager or using SQL-SMO, but for my purposes I need to use
T-SQL.
Thanks in advance!
Ryanfrom BOL : " IDENTITY Specifies that the new column is an identity column.
....."
This means you can only specify it when you add the column to the table.
If you can, use SQL Enterprise Manager, Design the table and generate the
script.
You'll see it generates something like this (so it creates / copies / drops)
:
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
CREATE TABLE dbo.Tmp_TJOBIdoc_exe
(
column_a int NULL,
column_b int NOT NULL IDENTITY (1, 1),
column_c int NULL
) ON [PRIMARY]
GO
SET IDENTITY_INSERT dbo.Tmp_TJOBIdoc_exe ON
GO
IF EXISTS(SELECT * FROM dbo.TJOBIdoc_exe)
EXEC('INSERT INTO dbo.Tmp_TJOBIdoc_exe (column_a, column_b, column_c)
SELECT column_a, column_b, column_c FROM dbo.TJOBIdoc_exe TABLOCKX')
GO
SET IDENTITY_INSERT dbo.Tmp_TJOBIdoc_exe OFF
GO
DROP TABLE dbo.TJOBIdoc_exe
GO
EXECUTE sp_rename N'dbo.Tmp_TJOBIdoc_exe', N'TJOBIdoc_exe', 'OBJECT'
GO
ALTER TABLE dbo.TJOBIdoc_exe ADD CONSTRAINT
column_a_un UNIQUE NONCLUSTERED
(
column_a
) ON [PRIMARY]
GO
COMMIT
jobi
"Ryan Clarke" <ryan@.turfsport.co.za> wrote in message
news:bfoj7v$q7q$1@.ctb-nnrp2.saix.net...
> Hi All
> Is it possible to alter an EXISTING column to make it an IDENTITY seed
> column using T-SQL. I've looked at the BOL help for alter table/column but
> can't seem to decipher how it should be done. It can be easily done using
> enterprise manager or using SQL-SMO, but for my purposes I need to use
> T-SQL.
> Thanks in advance!
> Ryan
>

No comments:

Post a Comment