I am new SQL world I want to neither rebuild the whole table nor add a new column.
Asked
Active
Viewed 157 times
-5
-
You can't alter the existing columns for identity. – ahmed abdelqader May 03 '18 at 06:24
-
Why is it so? help me – Ashish Gupta May 03 '18 at 06:26
-
Can someone help in deactivating my stack overflow account – Ashish Gupta May 03 '18 at 06:33
2 Answers
0
//Drop the column
Alter TABLE [dbo].[t_name]
drop column [columnname]
//create a new column with identity and with previous column name
Alter TABLE [dbo].[t_name]
add [columnname] [int] IDENTITY(1,1) NOT NULL

Ajay Venkata Raju
- 1,098
- 12
- 22
0
if you want to alter existing table column you can try this: replace Tmp_example1 with tmp_yourtablename replace example1 with yourtablename replace eid with yourcolumnname
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
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
GO
CREATE TABLE dbo.Tmp_example1
(
eid INT NOT NULL IDENTITY (1, 1)
) ON [PRIMARY] GO
SET IDENTITY_INSERT dbo.Tmp_example1 ON
GO
IF EXISTS(SELECT * FROM dbo.example1)
EXEC('INSERT INTO dbo.Tmp_example1 (eid)
SELECT eid FROM dbo.example1 WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT dbo.Tmp_example1 OFF
GO
DROP TABLE dbo.example1
GO
EXECUTE sp_rename N'dbo.Tmp_example1', N'example1', 'OBJECT'
GO
COMMIT

Ajay Venkata Raju
- 1,098
- 12
- 22