繁体   English   中英

如何查找给定月份是否已存在于数据库表中

[英]How to find whether a given month already exists in a database table

如果我有这样的数据

case 1

   code    start month    end month
  winter     january       march 
  summer     march         april
  spring     may           december

case 2

   code    start month    end month
  winter     march         march 
  summer     april         january
  spring     february      february

如果我要再次输入,请从下个月开始。 我应该验证我所给的月份是否已经存在于任何季节的表中。

我想在查询的帮助下进行验证,这样我就不会输入重复项。

这几个月只是字符串。 这些值不包括年份–
我希望确保我在新行中输入的新月份不会落在以前记录中已经给定的月份之间,并且该期间在一年中也会重叠。

尝试这个...

declare @startmonth varchar(10)
declare @endmonth varchar(10)
set @startmonth = 'march'
set @endmonth = 'may'
declare @stmonth int
declare @edmonth int

set @stmonth = DATEPART(mm,CAST(substring(@startmonth,0,4) + ' 1900' AS DATETIME))
set @edmonth = DATEPART(mm,CAST(substring(@endmonth,0,4) + ' 1900' AS DATETIME))
print(@stmonth + ' ' + @edmonth)

declare @checkexist int
set @checkexist = 0
declare @te int
if(@edmonth < @stmonth)
begin
    set @te = @stmonth
    set @stmonth = @edmonth
    set @edmonth = @te
end
set @te = @stmonth
while (@te < @edmonth)
begin
declare @count int
SELECT @count = count(code) from tablename where DATEPART(mm,CAST(substring(start_month,0,4)+ ' 1900' AS DATETIME)) <= @te and DATEPART(mm,CAST(substring(start_month,0,4)+ ' 1900' AS DATETIME)) >= @te
if(@count > 1)
    begin
    set @checkexist = 1
    break
    end
set @te = @te + 1
end

if(@checkexist = 0)
begin
 --'insert statement
end

SQL Server解决方案:

INSERT INTO atable (code, [start month], [end month])
SELECT u.code, u.[start month], u.[end month]
FROM (
  SElECT
    *,
    start_month_num = MONTH(CAST([start month] + ' 1, 2000' AS datetime)),
    end_month_num   = MONTH(CAST([end month]   + ' 1, 2000' AS datetime))
  FROM (
    @code AS code,
    @start_month AS [start month],
    @end_month AS [end month]
  ) x
) u
  LEFT JOIN (
    SElECT
      start_month_num = MONTH(CAST([start month] + ' 1, 2000' AS datetime)),
      end_month_num   = MONTH(CAST([end month]   + ' 1, 2000' AS datetime))
    FROM atable
  ) t ON u.start_month_num BETWEEN t.start_month_num AND t.end_month_num +
           CASE WHEN t.end_month < t.start_month THEN 12 ELSE 0 END
         OR
         t.start_month_num BETWEEN u.start_month_num AND u.end_month_num +
           CASE WHEN t.end_month < t.start_month THEN 12 ELSE 0 END
WHERE t.code IS NULL

@code@start_month@end_month是要插入的值。 如果指定范围与表中已存储的任何范围都不重叠,则将插入这些值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM