Question : Dynamic sql insert identity

I have a strored procedure that creates tables adding a prefix to the table name and then inserts data into the table.
I am doing this using dynamic sql. The problem is that when I try to turn on the insert identity I get an error.

SELECT @sql = 'SET IDENTITY_INSERT ['+ @prefix + '_Advancements] ON'
EXEC @sql

All the other code works great. If I do Select @sql to view the output it shows:
SET IDENTITY_INSERT Test_Advancements ON
and if I run this code it works fine. So what would stop this from executing correctly

Here is a bigger portion of the sp. Once I get this to work then I will add the data.

CREATE PROCEDURE Create_New_Tables
@prefix nvarchar(15)

 AS

DECLARE @sql nvarchar(4000)

/*CREATE ADVANCEMENTS TABLE*/

-- Table structure for table '_Advancements'
SELECT @sql = 'IF EXISTS (SELECT * FROM sysobjects WHERE (name = "' + @prefix + '_Advancements")) DROP TABLE ['+ @prefix + '_Advancements]'
EXEC (@sql)

SELECT @sql = 'CREATE TABLE ['+ @prefix + '_Advancements] ('+
'      [Advancement_ID] [int] IDENTITY (1, 1) NOT NULL ,'+
'      [Advancement_Name] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,'+
'      [Advancement_Description] [nvarchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,'+
'      [Advancement_Time] [decimal](18, 0) NOT NULL ,'+
'      [Advancement_Available] [datetime] NULL ,'+
'      [Advancement_Cost] [decimal](18, 0) NULL ,'+
'      [Advancement_Req1] [int] NULL ,'+
'      [Advancement_Req2] [int] NULL ,'+
'      [Advancement_Req3] [int] NULL ,'+
'      [Advancement_Timestamp] [datetime] NOT NULL CONSTRAINT [DF_'+ @prefix + '_Advancements_Advancement_Timestamp] DEFAULT (getdate()),'+
'      CONSTRAINT [PK_'+ @prefix + '_Advancements] PRIMARY KEY  CLUSTERED '+
'      ('+
'            [Advancement_ID]'+
'      )  ON [PRIMARY] '+
') ON [PRIMARY]'
EXEC (@sql)

-- Dumping data for table _Advancements'
--
-- Enable identity insert
SELECT @sql = 'SET IDENTITY_INSERT ['+ @prefix + '_Advancements] ON'
EXEC @sql
-- Disable identity insert
SELECT @sql = 'SET IDENTITY_INSERT ['+ @prefix + '_Advancements] OFF'
EXEC @sql
GO

The Errors that I get are:
Server: Msg 203, Level 16, State 2, Procedure Create_New_Tables, Line 36
The name 'SET IDENTITY_INSERT [Test_Advancements] ON' is not a valid identifier.

Answer : Dynamic sql insert identity

Within the one QA session, the insert will stay ON, but if you open up another QA window,  it will be OFF, even though it is currently ON in the first session. Similarly, when you do EXEC it is a new scope.
Random Solutions  
 
programming4us programming4us