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

前端 未结 8 965
暗喜
暗喜 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:23

    If you want to know about the session variable... Good question, but I cant see where this information would be usefull. In normal execution to check a normal table response to an insert, this should work!

    -- If you only want to know if there is identity insert on a given table:

    select is_identity
    from sys.columns
    where object_id = OBJECT_ID('MyTable', 'U') and name = 'column_Name'
    

    -- Or... Use this if you want to execute something depending on the result:

    if exists (select *
    from sys.columns
    where object_id = OBJECT_ID('MyTable', 'U') and is_identity = 1)
    ... your code considering identity insert
    else
    ... code that should not run with identity insert
    

    Have fun!

    0 讨论(0)
  • 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 
    
    0 讨论(0)
提交回复
热议问题