我正在使用以下代码在 SQL Server 中创建序列。但它将错误显示为未知对象类型。请给出解决方案
这是我的代码:
create sequence seqval start with 100 increment by 1 minvalue 0 maxvalue 0 no cycle
no cache;
提前致谢
我正在使用以下代码在 SQL Server 中创建序列。但它将错误显示为未知对象类型。请给出解决方案
这是我的代码:
create sequence seqval start with 100 increment by 1 minvalue 0 maxvalue 0 no cycle
no cache;
提前致谢
你可以这样做。
--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
创建一个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
列重置为其最初声明的种子值。
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。
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
我们不能在 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
你确定你在运行 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.