有一张表 Test(ID int null)有3000条数据,ID开始没有值,都是null,现在要求ID有值,从第一条记录开始,值为1 ,然后最后一条值为3000。我用重新设定ID为identity的方法,提示错误,后来想到用SQL更新这列值,SQL如何写呢?

解决方案 »

  1.   

    alter table Test drop column ID
    alter table Test add column ID int identity(1,1)
      

  2.   

    alter table test drop column id alter table test add id(int identity (1,1))
      

  3.   


    declare @n int
    set @n=0update tableb 
    set @n=@n+1,qty=@n
      

  4.   

    --参考
    --创建测试表
    CREATE TABLE t1(ID int IDENTITY,A int)
    GO
    --插入记录
    INSERT t1 VALUES(1)
    GO--1. 将IDENTITY(标识)列变为普通列
    ALTER TABLE t1 ADD ID_temp int
    GOUPDATE t1 SET ID_temp=ID
    ALTER TABLE t1 DROP COLUMN ID
    EXEC sp_rename N't1.ID_temp',N'ID',N'COLUMN'
    INSERT t1 VALUES(100,9)
    GO--2. 将普通列变为标识列
    CREATE TABLE t1_temp(ID int,A int IDENTITY)
    SET IDENTITY_INSERT t1_temp ON
    INSERT t1_temp(ID,A) SELECT * FROM t1
    SET IDENTITY_INSERT t1_temp OFF
    DROP TABLE T1
    GOEXEC sp_rename N't1_temp',N't1'
    INSERT t1 VALUES(109999)
    GO--显示处理结果
    SELECT * FROM t1
    /*--结果:
    ID          A 
    ----------------- ----------- 
    1           1
    100         9
    109999      10
    --*/
      

  5.   

    declare @n int
    set @n=0update tableb 
    set @n=@n+1,qty=@n支持这个方法!
      

  6.   

    1樓語法有誤
    alter table Test add column ID int identity(1,1)--紅色去掉只用用刪除再新增列,如果要不改變ID列在表的排序,可用企業管理器調整,或新建一個新表再導入
      

  7.   

    多了个括号
    alter table test drop column id alter table test add id int identity (1,1)
      

  8.   

    alter table Test add column ID int identity(1,1) --这个纠正一下