为每行添加一个唯一值的列ID

时间:2015-06-18 09:33:48

标签: sql sql-server

我有一个包含现有数据的现有表,我想添加具有自动增量的新列(名为ID),我想为每一行添加一个唯一值。

除了获取所有数据并为每一行执行更新以设置此值之外,还有其他方法吗?

1 个答案:

答案 0 :(得分:5)

如果您需要SELECT

SELECT *, ROW_NUMBER() OVER(ORDER BY ...A ORDER VALUE) as id
FROM yourTable

如果你需要在桌子上:

ALTER TABLE yourTable ADD id int identity(1,1)

以下是ALTER TABLE

输出的演示
CREATE TABLE #temp(name nvarchar(50))

INSERT INTO #temp(name) VALUES(N'Kai'),(N'Bernd'),(N'Flo'),(N'Pete')

SELECT * FROM #temp

-- This is what you need to do
ALTER TABLE #temp 
ADD id int identity(1,1) -- This will add and fill the new column

SELECT * FROM #temp

DROP TABLE #temp
相关问题