--we have data in that table then we follow below steps to add identity
--And also next inserted value should be resse to max+1
--And also next inserted value should be resse to max+1
/*
A table without an IDENTITY column.
We want to add the IDENTITY property to the Col1 column
*/ CREATE TABLE AddIdentity ( Col1 INT NOT NULL, Col2 VARCHAR(10) NOT NULL, CONSTRAINT pkAddIdentity PRIMARY KEY (Col1)
); /*
A temporary table, with the schema identical to the AddIdentity table,
except that the Col1 column has the IDENTITY property
*/ CREATE TABLE AddIdentityTemp ( Col1 INT NOT NULL IDENTITY(1,1), Col2 VARCHAR(10) NOT NULL, CONSTRAINT pkAddIdentityTemp PRIMARY KEY (Col1)
); -- Insert test data INSERT INTO AddIdentity (Col1, Col2) VALUES (1, 'a'); -- Switch data into temporary table ALTER TABLE AddIdentity SWITCH TO AddIdentityTemp; -- Look at the switched data SELECT Col1, Col2 FROM AddIdentityTemp; -- Drop the original table, which is now empty DROP TABLE AddIdentity; -- Rename the temporary table, and all constraints, to match the original table EXEC sp_rename 'AddIdentityTemp', 'AddIdentity', 'OBJECT'; EXEC sp_rename 'pkAddIdentityTemp', 'pkAddIdentity', 'OBJECT'; -- Reseed the IDENTITY property to match the maximum value in Col1 DBCC CHECKIDENT (AddIdentity, RESEED); -- Insert test data INSERT INTO AddIdentity (Col2) VALUES ('b'); -- Confirm that a new IDENTITY value has been generated SELECT Col1, Col2 FROM AddIdentity;
-------BY USING ALTER TO ADD IDENTITY TO THAT TABLE
DECLARE @max_identity NVARCHAR(20)
DECLARE @SQL NVARCHAR(MAX)=''
SELECT @max_identity=ISNULL(MAX(responsys_complaint_id)+1,1) FROM Email.dbo.Responsys_Complaint
SET @SQL=@SQL+'ALTER TABLE Email.dbo.Responsys_Complaint ALTER COLUMN responsys_complaint_id IDENTITY(CAST('+@max_identity+' AS INT),1) NOT NULL'
PRINT @SQL
--EXEC(@SQL)