使用 SQL Server 生成自定义自动生成序列的最佳方法是什么?
这是我的要求:
我的应用程序托管在 10 台未互连的独立服务器上。
每个实例都应该生成一个序列号,所有这些数据将使用 SQL Server 的合并复制合并到所有数据库中。
生成的序列在所有服务器中应该是唯一的。
为了实现这一点,我创建了一个函数来为序列号添加服务器 id 前缀,并将其用作计算列。但是当我添加数据时,出现以下异常:
“已超出最大存储过程、函数、触发器或视图嵌套级别(限制为 32)。”
这是我的表和函数。请提出更好的方法。
create table Customers
(
CID int identity not null primary key,
CustomerName varchar(50)
)
ALTER function [dbo].[NextCustomerNumber]()
returns bigint
as
begin
declare @lastval bigint
declare @serverId int
declare @newval bigint
set @lastval = (select max(CustomerNumber) from Customers)
set @serverId= 1 -- Server ID pulls from some settings
set @newval=CONVERT(bigint, (CAST(@serverId as varchar(2))+CONVERT( varchar(10),(RIGHT(@lastval,(LEN(@lastval)-LEN(@serverId)))+1))))
return @newval
end
Alter table Customers add CustomerNumber …Run Code Online (Sandbox Code Playgroud)