Sql 服务器不是唯一的自增列

Sql server not unique auto-increment column

假设我的 MSSQL Server 数据库中有一个名为 [dbo].[Order] 的 table,如下所示:

CREATE TABLE [dbo].[Order] (
    [Id]                INT             IDENTITY (1, 1) NOT NULL,
    [NumberInMonth]     INT             NOT NULL,
    [Amount]            DECIMAL (18, 2) NOT NULL,
    CONSTRAINT [PK_dbo.Order] PRIMARY KEY CLUSTERED ([Id] ASC)
);

我希望 NumberInMonth 列为:

而且我还想有一种方法来进行计划操作,它将在每个月的第一天NumberInMonth 重置计数器

如何实现?

一个简单的序列就可以提供自增功能:

CREATE SEQUENCE seq_numberInMonth as int START WITH 1 INCREMENT BY 1;

CREATE TABLE [dbo].[Order] (
    [Id]                INT             IDENTITY (1, 1) NOT NULL,
    [NumberInMonth]     INT             NOT NULL DEFAULT(next value for seq_numberInMonth),
    [Amount]            DECIMAL (18, 2) NOT NULL,
    CONSTRAINT [PK_dbo.Order] PRIMARY KEY CLUSTERED ([Id] ASC)
);

测试:

INSERT INTO [Order] (Amount) VALUES (12.0), (13.0), (14.0)

SELECT *
FROM [Order]

结果:

Id      NumberInMonth   Amount
1       1               12,00
2       2               13,00
3       3               14,00

您可以很容易地在每个月的 1 号 create a scheduled job 到 运行 并重新设置顺序:

ALTER SEQUENCE seq_numberInMonth RESTART WITH 1 ;  

在 t-sql 中创建作业可以这样完成:(没有测试,但根据以下链接应该可以工作):

How to: Create a SQL Server Agent Job
Create a Job

USE msdb ;  
GO  
EXEC dbo.sp_add_job  
    @job_name = N'seq_numberInMonth reset' ;  
GO  
EXEC sp_add_jobstep  
    @job_name = N'seq_numberInMonth reset',  
    @step_name = N'1st',  
    @subsystem = N'TSQL',  
    @command = N'ALTER SEQUENCE seq_numberInMonth RESTART WITH 1 ;',   
    @retry_attempts = 5,  
    @retry_interval = 5 ;  
GO  
EXEC sp_add_schedule @schedule_name =  'every 1st of the month' 
    , @enabled = 1
    , @freq_type = 16
    , @freq_interval = 1

GO  
EXEC sp_attach_schedule  
   @job_name = N'seq_numberInMonth reset',  
   @schedule_name = N'every 1st of the month';  
GO  
EXEC dbo.sp_add_jobserver  
    @job_name = N'seq_numberInMonth reset';  
GO