How to set identity column to created table in SQL server

蓝咒 提交于 2019-12-18 19:27:12

问题


I created a table in SQL Server like this:

CREATE TABLE [UserName]
(
   [ID] [int] NOT NULL ,
   [Name] [nvarchar] (50) NOT NULL ,
   [Address] [nvarchar] (200) NULL

   CONSTRAINT [PK_UserName] PRIMARY KEY CLUSTERED ([ID] ASC)
) ON [PRIMARY]
GO

If I want to make ID an identity column, what do I need? Do I need to drop and create this table and set ID to [ID] [int] IDENTITY(1,1) NOT NULL .

By using drop and create, all of data from UserName table are lost .

Is there another way to set IDENTITY COLUMN to created table's column without losing data?

I use SQL Server 2008 R2 :)


回答1:


ALTER TABLE [UserName] DROP COLUMN [ID];

ALTER TABLE [UserName] 
    ADD [ID] integer identity not null;



回答2:


Try this one -

DECLARE @temp TABLE
(
      ID INT NOT NULL 
    , Name NVARCHAR(50) NOT NULL 
    , [Address] NVARCHAR(200) NULL
) 

INSERT INTO @temp (ID, Name, [Address])
SELECT ID, Name, [Address]
FROM dbo.UserName

DROP TABLE dbo.UserName

CREATE TABLE dbo.UserName
(
      [ID] [int] IDENTITY(1,1) NOT NULL 
    , [Name] [nvarchar] (50) NOT NULL 
    , [Address] [nvarchar] (200) NULL
CONSTRAINT [PK_UserName] PRIMARY KEY CLUSTERED 
([ID] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

SET IDENTITY_INSERT dbo.UserName ON

INSERT INTO dbo.UserName (ID, Name, [Address])
SELECT ID, Name, [Address] 
FROM @temp

SET IDENTITY_INSERT dbo.UserName OFF



回答3:


The easiest way:-

  1. Right click on the table in object explorer and select 'Design'
  2. Select the column for which you want to set identity and go to Column Properties
  3. Under 'Identity Specification' change 'Is Identity' to 'Yes'
  4. Click Save.... Done :)

Hope This Helps




回答4:


Here is a solution that is minimally logged.

SELECT 
    IDENTITY(INT, 1,1) AS ID,
    Name, [Address]
INTO dbo.UserName_temp
FROM dbo.UserName;


ALTER TABLE dbo.UserName_temp
    ADD CONSTRAINT [PK_UserName] PRIMARY KEY CLUSTERED;

DROP TABLE dbo.UserName;

EXEC sp_rename 'dbo.UserName_temp', 'UserName';

SRC: http://sqlmag.com/sql-server/appending-identity-column-temporary-table

But the IDENTITY() function can "only in a SELECT statement with an INTO table clause."

http://msdn.microsoft.com/en-us/library/ms189838.aspx



来源:https://stackoverflow.com/questions/16188278/how-to-set-identity-column-to-created-table-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!