SQL Server 2008中的Identity函数

在此教程中,将介绍Identity() 函数。 此函数用于在给定列中插入自动生成的值。

Identity() 函数用于为一列分配一个自动递增的数字。 该列可以是 int、boirnt、decimal 或者 smallint 类型。

语法

Column_Name Data_Type identity(m,n)

其中:

column_name 列的名称。

data_type 是给定列的数据类型。

m是将分配给表中第一行的值。

n是递增以添加表中的下一个行的M值。

SQL Server Identity函数示例

创建数据表

create table student(roll_num int identity(1,1), stu_Fname varchar(10), stu_Lname varchar(10))

insert into student

select 'a','b' union all

select 'c','d' union all

select 'e','f' union all

select 'g','h' union all

select 'i','j'

select * from student

使用 SELECT INTO 创建新表,其中新表中需要id值。

select

(

select

count (*)

from

student as T2

where

T2.stu_Fname <= T1.stu_Fname)

AS rownum,

stu_Fname

from

student as T1

order by

stu_Fname

drop table student

go
日期:2020-06-02 22:18:01 来源:oir作者:oir