0
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,该怎么做?

4

1 回答 1

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
于 2013-05-16T13:48:53.513 回答