您的位置:首页 > 博客中心 > 数据库 >

SQL Server identity种子

时间:2022-03-14 00:34

背景:

      用identity修饰列可以使它自动增长

例了:

      create table T(ID int not null identity(1,1),
      Data nvarchar(32));

      插入数据

     declare @i as int =1;
     while(@i<10)
     begin
           insert into T values(replicate(cast(@i as nchar(1)),10))
           set @i = @i +1;
    end

         gxlsystem.com,布布扣

        用dbcc checkident(‘Table_Name‘); 查看表的种子值。

        gxlsystem.com,布布扣

        删除数据:

                    delete from T
                    where ID >1;
                    go

                    dbcc checkident(‘Table_Name‘);--这时种子值还是9

       再次插入数据:

                        insert into T(Data) values(‘AAAA‘); 

       查看数据:

                  gxlsystem.com,布布扣

解决方法、

            重设种子值:

                          dbcc checkident(‘T‘,reseed,2);-- 到这一步问题就已经解决了

            插入数据:

                       insert into T(Data) values(‘BBB‘);

            输出:

                   select * fom T;

                   gxlsystem.com,布布扣

重点:

      这个种子值是  2  而表是有一个值是 10 如果一直长下去,会发生什么事呢?让我们多插入几条数据看一下

      插入数据:

                 declare @i as int =1;
                 while(@i<10)
                 begin
                         insert into T values(replicate(‘NNN‘,10))
                         set @i = @i +1;
                 end

      输出:

            gxlsystem.com,布布扣

重点2、

        如果ID是主键什么办。

       第一步:

                删除数据         

               delete from T
               where Data like ‘%N%‘
               go

      第二步:

               加主键

              alter table T
              add constraint PK_ID primary key(ID);
              go

 

 

 

    

热门排行

今日推荐

热门手游