如何更新标识列值

时间:2013-05-15 11:55:04

标签: sql-server-2008-r2

ID  EmployeeName    Address PhoneNo EmailID DOB DOJ Designation Department  CraetedDate
2   Sabarish    Saidapet    9600387983  sabari@gmail.com    -1973   -2012   Ase Software    2013-05-15 17:07:43.223
10  Karthik Chrompet    9865028330  karthik@gmail.com   -1968   -2008   SoftwareEngineeer   Software    2013-05-15 15:40:41.613
15  Sabarish    Saidapet    9600387983  sabari@gmail.com    -1973   -2012   Ase Software    2013-05-15 17:07:12.003

在上表中,id列是identity列,我希望我的ID值为1,2,3,而不是2,10,15如何执行此操作?

1 个答案:

答案 0 :(得分:1)

试试这个 -

<强>查询:

IF OBJECT_ID (N'dbo.test') IS NOT NULL
   DROP TABLE dbo.test

CREATE TABLE dbo.test
(
      ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY
    , EmployeeName VARCHAR(50) NOT NULL
)

SET IDENTITY_INSERT dbo.test ON

INSERT INTO dbo.test 
(
      ID
    , EmployeeName
)
VALUES 
    (2, 'Sabarish Saidapet'), 
    (10, 'Karthik Chrompet'), 
    (15, 'Sabarish Saidapet')

SET IDENTITY_INSERT dbo.test OFF

SET IDENTITY_INSERT dbo.test ON

DECLARE @temp TABLE
(
        ID INT NOT NULL
      , EmployeeName VARCHAR(50) NOT NULL
)

INSERT INTO @temp (EmployeeName, ID)
SELECT 
      t.EmployeeName 
    , ROW_NUMBER() OVER (ORDER BY (SELECT 1))
FROM dbo.test t

TRUNCATE TABLE dbo.test
--DELETE FROM dbo.test

INSERT INTO dbo.test (ID, EmployeeName)
SELECT ID, EmployeeName FROM @temp

SET IDENTITY_INSERT dbo.test OFF

INSERT INTO dbo.test (EmployeeName)
VALUES ('test 4')

SELECT * 
FROM dbo.test t

<强>输出:

ID          EmployeeName
----------- --------------------------------------------------
1           Sabarish Saidapet
2           Karthik Chrompet
3           Sabarish Saidapet
4           test 4