http://www.sqlfiddle.com/#!18/c913b/1
CREATE TABLE Table1 (
[ID] int PRIMARY KEY,
[Date] date,
[Name] varchar(40)
);
INSERT INTO Table1 (ID, date, Name )
Values ('1','07-20-18','Fred'),
('2','07-15-18','Sam'),
('3','07-20-18','Ben'),
('4','07-19-18','Simon'),
('5','07-25-18','Dave');
当前查询:
DECLARE @StartDate AS DATETIME,
@CurrentDate AS DATETIME
SET @StartDate = GETDATE() -30
SET @CurrentDate = GETDATE()
SELECT [ID], [Date], [Name]
FROM Table1
WHERE [Date] BETWEEN @StartDate AND @CurrentDate
当前结果:
| ID | Date | Name |
|----|------------|-------|
| 1 | 2018-07-20 | Fred |
| 2 | 2018-07-15 | Sam |
| 3 | 2018-07-20 | Ben |
| 4 | 2018-07-19 | Simon |
此查询与为@startdate变量设置的日期范围进行比较。任何想运行查询的人都可以将其更改为任何内容。问题是,如果有人选择崩溃的日期范围很大。如果有一种方法,我可以设置一条if语句,如果例如他们试图运行一个查询超过100天,则会抛出一条错误消息。
结果:错误-请降低日期范围
这有可能吗?