检查位数或其范围

Check the number of digits or their range

我试图创建一个 table 来保存展会,我需要将年份和月份保存到不同的列中。

我的后端和前端开发人员检查数据有问题。我需要检查年份是 4 数字和 1-12 之间的月份。 速度对我来说很重要

CREATE TABLE [dbo].[TradeShows](
    [TradeShowsID] [bigint] IDENTITY(1,1) NOT NULL,
    [TradeShowsName] [nvarchar](100) NULL,
    [YearAttended] [smallint] NULL,
    [MonthAttended] [tinyint] NULL,
 CONSTRAINT [PK_TradeShows] PRIMARY KEY CLUSTERED 
(
    [TradeShowsID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

只需使用check约束:

alter table TradeShows add constraint chk_tradeshows_year
    check (YearAttended >= 2000 and YearAttended < 2100);

alter table TradeShows add constraint chk_tradeshows_month
    check (MonthAttended >= 1 and MonthAttended <= 12);

或者,您可以花点时间验证两者是否构成一个有效日期:

alter table TradeShows add constraint chk_tradeshows_year_month
    check (try_convert(date, concat('-', YearAttended, MonthAttended, '-01')) is not null);