如果记录在90天内不存在,则需要将其添加到SQL中;如果记录在90天内存在,则需要避免

如果记录在90天内不存在,则需要将其添加到SQL中;如果记录在90天内存在,则需要避免,sql,sql-server,tsql,Sql,Sql Server,Tsql,[在此处输入图像描述][1] 我只想获取新记录,以便它必须通过一个条件,即如果它在90天内存在,则不能插入到表中,如果它在90天内不存在,则需要将该特定记录插入到表中 我已将查询编写如下: select * from driver where CURRENT_TIMESTAMP - 90 > (select max(Createddate) from Driver

[在此处输入图像描述][1]

我只想获取新记录,以便它必须通过一个条件,即如果它在90天内存在,则不能插入到表中,如果它在90天内不存在,则需要将该特定记录插入到表中

我已将查询编写如下:

select * 
from driver 
where CURRENT_TIMESTAMP - 90 > (select max(Createddate) 
                                from Driver 
                                where DriverID = '1x123' 
                                group by DriverID)

请参见屏幕截图:

这就是您要查看的内容吗

select '1x123', GetDate() 
where not exists ( select 1 
                     from driver  
                    where DateDiff(dd, Createddate, GetDate()) < 90 
                      and DriverID = '1x123' )

这听起来是一个非常简单的测试条件。请参见下面的自包含示例:

declare @tmp table(driverid nvarchar(10),createddate datetime)

--insert a sample record first
insert into @tmp
select '7x123','2015-6-20'


declare @incomingvalue nvarchar(10) = '7x123';

declare @now datetime = getdate();
declare @threshold datetime = @now - 90;

if exists(select * from @tmp where driverid = @incomingvalue and createddate >= @threshold)
begin
  print 'Already a record on file within 90 days, no action taken';
end
else
begin
  insert into @tmp
  select @incomingvalue, @now
  print 'Nothing on file in last 90 days, record inserted';
end

select * from @tmp

运行问题中的查询时会发生什么情况?请调整屏幕截图的大小。插入..选择..不存在的地方..@DanBracuk它没有显示output@TabAlleman你能很快地写下查询库吗?它工作得很好。因为你在@threshold中使用了datetime而不是date,所以它会检查一天中的时间,而不仅仅是日期。这可能是也可能不是OP的意图。值得注意的是,这需要包装在一个合适的事务中,以避免两个用户同时通过exists测试,然后两个用户都插入行。嘿@frisbee感谢它正在执行的查询您可以单击复选标记以指示它是正确的答案如果我不知道ID,那么我在这方面需要采取什么方法如果id是相同的,这就是我们所知道的,那么在这种情况下,你能提出一个问题吗?如果你没有一个已知的id,那么接受的答案是如何工作的?据我所知,这只是已接受答案的一个简短版本。谢谢你的回答,我没有其他方法可以说你的答案是正确的,所以请不要介意将你的答案作为参考correct@frisbee