How do you check if IDENTITY_INSERT is set to ON or OFF in SQL Server?

前端 未结 8 984
暗喜
暗喜 2020-12-09 00:52

I\'ve searched for this, but threads in which it appeared tended to have answers from people who didn\'t understand the question.

Take the following syntax:

<
8条回答
  •  青春惊慌失措
    2020-12-09 01:24

    You can discover whether or not identity_insert is on, and if so for what table using the code below.

    declare @tableWithIdentity varchar(max) = '';
    SET IDENTITY_INSERT ExampleTable ON
    
    begin try
      create table #identityCheck (id int identity(1,1))
      SET IDENTITY_INSERT #identityCheck ON
      drop table #identityCheck
    end try
    begin catch
      declare @msg varchar(max) = error_message()
      set @tableWithIdentity= @msg;
      set @tableWithIdentity = 
      SUBSTRING(@tableWithIdentity,charindex('''',@tableWithIdentity,1)+1, 10000)
    
      set @tableWithIdentity = SUBSTRING(@tableWithIdentity,1, charindex('''',@tableWithIdentity,1)-1)
    
      print @msg;
      drop table #identityCheck
    end catch
    
    if @tableWithIdentity<>''
    begin
      print ('Name of table with Identity_Insert set to ON: ' + @tableWithIdentity)
    end
    else
    begin
      print 'No table currently has Identity Insert Set to ON'
    end 
    

提交回复
热议问题