6

我正在使用以下代码在 SQL Server 中创建序列。但它将错误显示为未知对象类型。请给出解决方案

这是我的代码:

create sequence seqval start with 100 increment by 1 minvalue 0 maxvalue 0 no cycle  
 no cache;

提前致谢

4

6 回答 6

9

你可以这样做。

--Create a dummy TABLE to generate a SEQUENCE. No actual records will be stored.
CREATE TABLE SequenceTABLE
(
    ID BIGINT IDENTITY  
);
GO

--This procedure is for convenience in retrieving a sequence.
CREATE PROCEDURE dbo.GetSEQUENCE ( @value BIGINT OUTPUT)
AS
    --Act like we are INSERTing a row to increment the IDENTITY
    BEGIN TRANSACTION;
    INSERT SequenceTABLE WITH (TABLOCKX) DEFAULT VALUES;
    ROLLBACK TRANSACTION;
    --Return the latest IDENTITY value.
    SELECT @value = SCOPE_IDENTITY();
GO

--Example execution
DECLARE @value BIGINT;
EXECUTE dbo.GetSEQUENCE @value OUTPUT;
SELECT @value AS [@value];
GO
于 2016-02-11T16:44:20.460 回答
2

创建一个Numbers表;这是一个关于这个主题的问题。让我们称之为dbo.Number

有一个带有标识列的表。将种子和步骤设置为适当的:

create table dbo.SequenceGenerator(ID int identity(1, 1), dummy int);

然后插入 numbers 表中的值并捕获新生成的标识值:

declare @HowMany int = 3;  -- This determines how large a sequence you receive
                           -- at each itteration
declare @NewSequenceValue table (ID int);

insert dbo.SequenceGenerator(dummy)
output INSERTED.ID 
    into @NewSequenceValue
select Number from dbo.Numbers
where Number <= @HowMany;

select * from @NewSequenceValue;

一定DELETE .. dbo.SequenceGenerator要不时进行,否则它会变大而没有额外的价值。不要这样做TRUNCATE- 这会将IDENTITY列重置为其最初声明的种子值。

于 2014-04-28T23:48:13.560 回答
2

SQL Server 2008 无法创建序列,序列对象通过当前版本适用于 SQL Server 2012。

https://msdn.microsoft.com/es-es/library/ff878091(v=sql.120).aspx

您可以在表中使用 IDENTITY,例如:

CREATE TABLE Person(
    Id int IDENTITY(1,1) NOT NULL PRIMARY KEY,
    Name varchar(255) NOT NULL
);

IDENTITY 的起始值为 1,对于每条新记录,它将递增 1。

http://www.w3schools.com/sql/sql_autoincrement.asp

于 2015-07-28T13:16:53.913 回答
1
WITH N0 as (SELECT 1 as n UNION ALL SELECT 1)
,N1 as (SELECT 1 as n FROM N0 t1, N0 t2)
,N2 as (SELECT 1 as n FROM N1 t1, N1 t2)
,N3 as (SELECT 1 as n FROM N2 t1, N2 t2)
,nums as (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as num FROM N3)
SELECT * FROM nums
于 2014-06-10T22:53:18.123 回答
0

我们不能在 SQL Server 2008 中轻松使用 Sequence。

您可以在 SQL Server 2008 中使用 CTE(通用表表达式)生成序列

WITH NUM_GEN (n) AS
     ( 
            SELECT 1 
            UNION 
                  ALLSELECT n+1 
            FROM  NUM_GEN 
            WHERE n+1< MAX_VALUE 
     ) 
SELECT n 
FROM   NUM_GEN
于 2019-09-12T05:33:08.290 回答
-3

你确定你在运行 2012 年?我没有遇到任何问题:

CREATE SEQUENCE seqval
START WITH 100
INCREMENT BY 1 
minvalue 100 maxvalue 10000 NO CYCLE

你的 0,0 值对我来说产生了一个语法错误,但一个清晰而简单的错误。

The minimum value for sequence object 'seqval' must be less than its maximum value.
于 2013-03-23T08:08:34.243 回答