SQL生成唯一ID号解决方案

时间:2025-01-24 20:26:51

新建存自增ID的表

CREATE TABLE [dbo].[IdentityID](
[TableName] [varchar](500) NOT NULL,
[NextID] [bigint] NOT NULL,
CONSTRAINT [PK_IdentityID] PRIMARY KEY CLUSTERED 
(
[TableName] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

写一个存储获取当前表的ID

CREATE PROCEDURE [dbo].[SP_GetIdentityID]
@TableName varchar(500)
AS
BEGIN
SET NOCOUNT ON;

declare @IdentityID bigint
set @IdentityID=1

begin tran
update IdentityID
set @IdentityID=NextID,NextID=NextID+1
where TableName=@TableName

if @@rowcount=0
begin            
insert into IdentityID(TableName,NextID)
values(@TableName,@IdentityID+1)
end
commit tran

return @IdentityID
END