Click here to Skip to main content
15,893,668 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to create a Generic Script to remove Identity Insert OFF of column for all tables of a DB in Sql server?

I am doing Archival Automation Process. I am migrating data from Original DB to Archival DB . I want to remove the Identity Insert of the columns in Archival DB and move the data from Original DB to Archival DB.

I have a single code as below:
SQL
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
Posted
Updated 17-Mar-15 22:01pm
v3
Comments
ZurdoDev 18-Mar-15 8:24am    
Where exactly are you stuck?
W Balboos, GHB 18-Mar-15 11:52am    
If the target file is an archive - exactly why do you need to preserve the identity property of field? It's generated in the source and should thus maintain its uniqueness the the target.

1 solution

Try this:

SQL
DECLARE @Rows INT = 0
DECLARE @SQL NVARCHAR(MAX)
DECLARE @MySQL AS TABLE
(
    ID int IDENTITY (1, 1) Primary key NOT NULL 
  , SQLTEXT NVARCHAR(MAX)
)

SET NOCOUNT ON
INSERT @MySQL
SELECT DISTINCT 'SET IDENTITY_INSERT ' + ST.TABLE_SCHEMA +'.'+ ST.TABLE_NAME + ' OFF'
FROM INFORMATION_SCHEMA.TABLES AS ST
INNER JOIN  INFORMATION_SCHEMA.COLUMNS AS SC
ON (ST.TABLE_SCHEMA +'.'+ ST.TABLE_NAME) = (SC.TABLE_SCHEMA +'.'+ SC.TABLE_NAME)
WHERE ST.TABLE_TYPE = 'BASE TABLE'
      AND
	  COLUMNPROPERTY(OBJECT_ID(ST.TABLE_SCHEMA +'.'+ ST.TABLE_NAME)
                      ,SC.COLUMN_NAME,'IsIdentity') = 1

ORDER BY 1

SELECT @Rows=COUNT(1) FROM @MySQL

WHILE(@Rows > 0)
BEGIN
	SELECT @SQL = SQLTEXT FROM @MySQL WHERE ID = @Rows

	EXECUTE sp_executesql @SQL

	SET @Rows = @Rows -1

END


Thanks,

Kuthuparakkal
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900