Setting identity_insert in dynamic sql

I am trying to set identity_insert on inside a dynamic sql statement.  For some reason, I keep getting the error "An explicit value for the identity column in table '#xxx' can only be specified when a column list is used and IDENTITY_INSERT is ON."  Since I am turning on identity_insert I should not be getting this error.  Help!

Note:  I must continue to use dynamic sql.  This code is an excerpt from a larger routine.


CREATE PROCEDURE dbo.spTestIdentityInsert
AS
declare @sql nvarchar (4000)
      
      create table #xxx
            (x_id int identity (1, 1))
      
      set @sql = 'set identity_insert #xxx on'  
      set @sql = @sql + ' '
      set @sql = @sql + 'insert #xxx values (1,2,3)'  

      exec sp_executesql @sql
GO
LVL 4
DrLechterAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Aneesh RetnakaranDatabase AdministratorCommented:
you should specify the column list here

set @sql = @sql + 'insert #xxx(x_id,i,j) values (1,2,3)'  
Aneesh RetnakaranDatabase AdministratorCommented:
this is the complete code

ALTER PROCEDURE dbo.spTestIdentityInsert
AS
declare @sql nvarchar (4000)

     create table #xxx
          (x_id int identity (1, 1),i int, j int )
     
     set @sql = 'set identity_insert #xxx on '
     set @sql = @sql + char(13)
     set @sql = @sql + 'insert #xxx(x_id,i,j) values (1,2,3)'  

    exec sp_executesql @sql

GO


exec spTestIdentityInsert


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
SireesCommented:
ALTER PROCEDURE dbo.spTestIdentityInsert
AS
declare @sql nvarchar (4000)

     create table #xxx
          (x_id int identity (1, 1),a int, b int )
     
     EXEC('SET IDENTITY_INSERT #xxx ON INSERT INTO #xxx (x_id,a,b) VALUES(1,2,3) SET IDENTITY_INSERT #xxx OFF')

GO
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.