Is there anyway to reset the identity of a Table Variable?

前端 未结 12 1960
无人及你
无人及你 2020-12-17 15:33

Say I have a table variable:

DECLARE @MyTableVar TABLE (ID INT IDENTITY(1,1), SomeData NVARCHAR(300))

After I have inserted 250 rows, I nee

相关标签:
12条回答
  • 2020-12-17 15:34

    Since you are re-using your table, if I got it right, how about you do not initialize your counters to 1 and instead use this as an example?

    DECLARE @ctr INT
    IF @ctr IS NULL or @ctr <= 0 --this part is to control @ctr value on loops
       SET @ctr = 1
    ELSE
       SELECT @ctr = MIN(id) FROM @tbl
    

    This way, you are not restarting your loop to 1 nor is there a need for you to truncate the table.

    0 讨论(0)
  • 2020-12-17 15:34

    I just had this idea and it works!!! :

    declare @TableVariable table (
        IdentityColumn int identity(1,1),
        SomeOtherValue int,
        DesiredResult int
    )
    declare @FirstIdentityValueEachTimeYouLoadDataToTable int
    declare @Count int
    set @Count = 1
    
    while @Count <= 5
    begin
        delete @TableVariable
    
        insert into @TableVariable (SomeOtherValue) select 45
        insert into @TableVariable (SomeOtherValue) select 90
        insert into @TableVariable (SomeOtherValue) select 2
    
        select @FirstIdentityValueEachTimeYouLoadDataToTable = min(IdentityColumn) from @TableVariable
    
        Update @TableVariable set DesiredResult = IdentityColumn - @FirstIdentityValueEachTimeYouLoadDataToTable + 1
    
        select * from @TableVariable
        set @Count = @Count + 1
    end 
    
    0 讨论(0)
  • 2020-12-17 15:38

    You can't reseed the identity value on a Table Variable but you can do the same thing with a Temp Table:

    CREATE  TABLE #TAB(ID INT IDENTITY,VALUE VARCHAR(10))
    DECLARE @RESEED INT = 32
    DBCC CHECKIDENT(#TAB,RESEED,@RESEED)
    INSERT INTO #TAB  
    SELECT 'TEST'
    SELECT * FROM #TAB  
    
    0 讨论(0)
  • 2020-12-17 15:38

    Is it possible to have another int column on your table variable and update that column with modulo after the insert is finished?

    declare @Mytablevar table
    (
    id int identity(1,1)
    ,id1 int
    somedata nvarchar(300)
    )
    
    -- insert your data as you would.  After insert is finished, do the following:
    
    update @mytablevar set id1 = case when id > 250 then id % 250 else id end
    
    0 讨论(0)
  • 2020-12-17 15:40

    If you are using SQL Server then use this DBCC CHECKIDENT('Customer', RESEED, 0) Where Customer is a table name. When you insert records into table after this command your primery key column value will be start from 1 again.

    Read this http://codedotnets.blogspot.in/2012/09/how-to-reset-identity-in-sql-server.html

    0 讨论(0)
  • 2020-12-17 15:42

    DELETE FROM does not reset identity. TRUNCATE does.

    0 讨论(0)
提交回复
热议问题