نحوه ایجاد Sequence و استفاده آن در Sql Server 2012
نویسنده: فرهاد فرهمندخواه
تاریخ: ۱۳۹۱/۰۷/۲۲ ۱۵:۸
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
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 [dbo].[SequenceTest] AS [int] START WITH 1 INCREMENT BY 1 MINVALUE 1 MAXVALUE 30 CYCLE CACHE GO
NEXT VALUE FOR [ database_name . ] [ schema_name . ] sequence_name [ OVER (<over_order_by_clause>) ]
Msg 11728, Level 16, State 1, Line 1 The sequence object 'SequenceTest' has reached its minimum or maximum value. Restart the sequence object to allow new values to be generated.
create table Kids ( ID int, Name varchar(50) ); Go insert Kids values (1,'Emma') , (1,'Tabitha') , (2,'Kendall') , (3,'Delaney') , (4,'Kyle') , (5,'Jessica') , (6,'Josh') , (7,'Kirsten') , (8,'Amanda') , (9,'Jimmy') ;
CREATE SCHEMA Samples ; GO
CREATE SEQUENCE Samples.Test
AS tinyint
START WITH 1
INCREMENT BY 1 ;
GO
SELECT NEXT VALUE FOR Samples.Test OVER (ORDER BY Name) AS NutID, ID, Name FROM test1.Kids WHERE Name LIKE '%e%' ;
set insert_identity tbl on update t set id = new_id from (select new_id = row_number() over(order by id), *) t set insert_identity tbl off
Select * into T from table_3
truncate table dbo.table_3
CREATE SEQUENCE testEventCounter
AS int
START WITH 1
INCREMENT BY 1 ;SET IDENTITY_INSERT table_3 on
INSERT INTO table_3 (ID, Descritp)
SELECT
NEXT VALUE FOR testEventCounter AS id
, Descritp
FROM TCREATE TABLE Table3
(
ID int PRIMARY KEY CLUSTERED
DEFAULT (NEXT VALUE FOR SequenceTest),
De nvarchar(300) NULL
) ;
GOUpdate table3 set id=(NEXT VALUE FOR testEventCounter )
SET IDENTITY_INSERT table_3 on
INSERT INTO table_3 (ID, Descritp)
SELECT
NEXT VALUE FOR testEventCounter (OVER ORDER BY ID) AS id
, Descritp
FROM T