想在已存在的表中增加一個ID列,並讓它自動的增加生成:
- 辦法一、在修改表時把Identity Specification下的Identify Increment設置為yes,並設置Identity Seed種子為1。
- 辦法二、執行SQL語句:
alter table tablename add id int identity(1,1)
若要在查詢中添加自增列,可以:
- 添加一列連續自增的ID,可用如下查詢語句:
select row_number() over (order by getdate()) as id, * from tablename
-
使用關鍵字IDENTITY:
select identity(int,1,1) as nid,* into #t from tablename; Select * from #t;
注意:
(1) 僅當 SELECT 語句中有 INTO 子句時,才能使用 IDENTITY 函數。

(2) 如果表中已有自增ID列,將無法使用 SELECT INTO 語句將標識列添加到臨時表,原因是該表的列 'ID' 已繼承了標識屬性。

