安全的 tsql 编号 int 技术

safe tsql Numbering int techniques

你好 Whosebugers!

我想知道是否有一种安全的方式,交易中的一系列数字就像 identity.My 的唯一目的是对 table 中的行进行分组,但我没有意思是 row_number()。 我想到了这个简单的查询,这安全吗? 这个table有自己的身份密钥

declare @mynextSecuenceNumber int
    select @mynextSecuenceNumber=isnull(max(secuencenumber+1),1) from mytable
insert into mytable (productID,customer,secuencenumber) values (@someval,@anotherval,@mynextSecuenceNumber)

编辑

背景

这样做的原因是下一个:

首先我正在接收汽车服务的汽车配件然后我为该接收生成一张票(我可以接收一个、两个、三个汽车零件)稍后我可以继续从相同的特定汽车服务接收汽车配件汽车零部件供应商或来自不同的供应商,但我希望能够重新生成事件或票证,否则我最终会查询服务以及与该服务或供应商相关的所有汽车零部件,我不知道事件我收到了什么在该操作中,最重要的是,我需要为与该汽车服务相关的所有汽车零部件提供另一个特定 ID。

顺便说一句,我在 sql 服务器 2008

注意

使用身份作为序列号可能会造成混乱,因为交易会在回滚和其他交易后增加价值 issues 所以请注意这一点,多亏了我接受的答案所提供的方法,我可以找到另一种方式来获得与交易一起首次出现在 link

当 SQL 2012 或更高版本不是一个选项时,这是 Microsoft 的可扩展建议,但您需要管理目标 table 中没有标识的序列号。这将创建一个单独的 table 来跟踪序列号,让 identity 完成一些繁重的工作,并通过清理使 table 大小保持最小。如果此负载变得过多,您可以在非高峰时间安排一些清理工作。

-- Create table for tracking the sequence
create table <tablename> (
      SeqID int identity(1,1) primary key
)
GO

-- Create procedure to return next sequence value
create procedure GetNewSeqVal_<tablename>
    @NextValue int output
as
begin
    declare @NewSeqValue int
    set nocount on
    insert into <tablename> DEFAULT VALUES
    set @NewSeqValue = scope_identity()
    delete from <tablename> with (readpast)
    set @NextValue = @NewSeqValue
end
go

-- Get next sequence
declare @seqId int
exec GetNewSeqVal_<tablename> @NextValue = @seqId OUTPUT

更多信息:http://blogs.msdn.com/b/sqlcat/archive/2006/04/10/sql-server-sequence-number.aspx