我在SQL Server中创建了一个表,如下所示:
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
如果我想将ID
作为标识列,我需要什么?我是否需要删除并创建此表并将ID
设置为[ID] [int] IDENTITY(1,1) NOT NULL
。
通过使用drop和create,UserName
表中的所有数据都将丢失。
是否有另一种方法可以将IDENTITY COLUMN
设置为创建的表格的列而不会丢失数据?
我使用SQL Server 2008 R2:)
答案 0 :(得分:14)
ALTER TABLE [UserName] DROP COLUMN [ID];
ALTER TABLE [UserName]
ADD [ID] integer identity not null;
答案 1 :(得分:5)
最简单的方法: -
希望这有助于
答案 2 :(得分:4)
试试这个 -
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 :(得分:0)
这是一个记录最少的解决方案。
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
但是IDENTITY()函数“只能在带有INTO表子句的SELECT语句中。”