我创建了一个像这样的表
CREATE TABLE [dbo].[sydShopOrder](
[rowNumber] [varchar](50) NULL,
[firstName] [varchar](50) NULL,
[lastName] [varchar](50) NULL,
[employeeNumber] [varchar](50) NULL,
[productID] [varchar](50) NULL,
[shopID] [varchar](50) NULL,
[location] [varchar](50) NULL,
[address] [varchar](50) NULL,
[department] [varchar](50) NULL,
[datestamp] [date] NULL
) ON [PRIMARY]
我打算将[rowNumber]
作为主键,并将其设为identity
列,并自动增加。但我忘了这么做。现在,数据库已在实时环境中启动并运行。我很晚才发现这个bug。有什么办法可以解决这个问题吗?将[rowNumber]
列设为标识并自动递增?
表的当前屏幕截图如下所示
答案 0 :(得分:2)
您可以删除[rownumber]
,然后添加身份
Alter Table [dbo].[sydShopOrder] Drop Column rownumber
Go
Alter Table [dbo].[sydShopOrder]
Add rownumber Int Identity(1, 1)
Go
如果要填充现有数据的标识字段,最好创建另一个临时表,并保留[dbo].[sydShopOrder]
的所有记录。在truncate
[dbo].[sydShopOrder]
之后,然后将该临时表中的值插入[dbo].[sydShopOrder]
CREATE TABLE #temp ([firstName] [varchar](50) NULL,
[lastName] [varchar](50) NULL,
[employeeNumber] [varchar](50) NULL,
[productID] [varchar](50) NULL,
[shopID] [varchar](50) NULL,
[location] [varchar](50) NULL,
[address] [varchar](50) NULL,
[department] [varchar](50) NULL,
[datestamp] [date] NULL)
INSERT INTO #temp
SELECT [firstName],[lastName],[employeeNumber],
[productID], [shopID],[location],
[address],[department],[datestamp]
FROM [dbo].[sydShopOrder]
TRUNCATE TABLE [dbo].[sydShopOrder]
INSERT INTO [dbo].[sydShopOrder]
SELECT * FROM #temp
以下是SQLFIDDLE
示例