使用过Oracle的都知道,Oracle中的自增是靠序列来完成的,在一定程度上蛮方便的。现在SQL 2012中也有序列了。来看看怎么做的吧!
SQL Server 现在将序列当成一个对象来实现,创建一个序列的语法如下:
CREATE SEQUENCE [schema_name . ] sequence_name [ AS [ built_in_integer_type | user-defined_integer_type ] ] [ START WITH <constant> ] [ INCREMENT BY <constant> ] [ { MINVALUE [ <constant> ] } | { NO MINVALUE } ] [ { MAXVALUE [ <constant> ] } | { NO MAXVALUE } ] [ CYCLE | { NO CYCLE } ] [ { CACHE [ <constant> ] } | { NO CACHE } ] [ ; ]
创建示例:
CREATE SEQUENCE Sequence_Test AS [bigint] START WITH 0 INCREMENT BY 1 MINVALUE 0 MAXVALUE 9223372036854775807 CACHE GO
使用序列:
SELECT NEXT VALUE FOR Sequence_Test 或者下面查询序列属性 SELECT * FROM sys.sequences WHERE name = 'Sequence_Test';
重置序列:
ALTER SEQUENCE Sequence_Test
RESTART WITH 1 ;
序列可定义为任意整数类型,如下面类型:
-
tinyint - 范围从 0 到 255
-
smallint - 范围从 -32,768 到 32,767
-
int - 范围从 -2,147,483,648 到 2,147,483,647
-
bigint - 范围从 -9,223,372,036,854,775,808 到 9,223,372,036,854,775,807
-
decimal 和 numeric,小数位数为 0。