简体   繁体   English

在T-SQL中计算日期差异

[英]Calculating variances on dates in T-SQL

Guys, I am trying to write a stored procedure in T-SQL (SQL Server) that will select records based on a date field, keeping a variance of minutes in mind. 伙计们,我正在尝试在T-SQL(SQL Server)中编写一个存储过程,该存储过程将基于日期字段选择记录,并牢记分钟的变化。 Something like this: 像这样:

CREATE PROCEDURE spGetCustomers(@DateRange DATETIME, @Variance int) AS
-- The next line is where I need help
-- I'm trying to subtract X amount of minutes from the date
-- So if @Variance = 4 AND @DateRange = '6/10/2009 1:15pm'
-- Then @StartDate should equal '6/10/2009 1:11pm'
DECLARE @StartDate = @DateRange - @Variance
-- I also need an @EndDate, which will be X amount of minutes
-- in the future. So if @Variance = 4 AND @DateRange = '6/10/2009 1:15pm'
-- Then @EndDate should equal '6/10/2009 1:19pm'
DECLARE @EndDate = @DateRange + @Variance

SELECT * FROM Customers WHERE Created BETWEEN @StartDate AND @EndDate

Hopefully this makes sense and someone can help me out! 希望这是有道理的,有人可以帮助我! Thanks in advance 提前致谢

Check this out: 看一下这个:

http://msdn.microsoft.com/en-us/library/ms186819(SQL.90).aspx http://msdn.microsoft.com/zh-CN/library/ms186819(SQL.90).aspx

The DATEADD function allows you to add virtually any part of a date to another date object, it should be everything you need. DATEADD函数允许您将日期的几乎任何部分添加到另一个日期对象,这应该是您需要的所有内容。

So basically do: 所以基本上可以这样做:

SELECT DATEADD(second, @Variance, @DateRange)

The following script provides an example that should get you started. 以下脚本提供了一个入门示例。

create table tmp_Customers
(
    ID int identity(1,1),
    CreatedDate datetime default getDate() not null,
    Description varchar(15)
);
go

insert into tmp_Customers(Description) values('SomeData');
insert into tmp_Customers(Description) values('SomeData2');
insert into tmp_Customers(Description) values('SomeData3');
go

create procedure usp_GetCustomers

    @iVarianceMinutes   int,
    @iDateRange         datetime

as

    set nocount on

    declare @startDate  datetime
    declare @endDate    datetime

    --Define the date ranges for the select query
    set @startDate = dateAdd(minute,-@iVarianceMinutes,@iDateRange)
    set @endDate = dateAdd(minute,@iVarianceMinutes,@iDateRange)

    --Get the Customers that were created within this time range.
    SELECT * 
    FROM tmp_Customers 
    WHERE CreatedDate >= @startDate and CreatedDate < @endDate 


return(0);
go


--Execute the procedure
declare @testDate datetime;
set @testDate = getDate();

exec usp_GetCustomers 5,@testDate 

--drop procedure usp_GetCustomers
--drop table tmp_Customers

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

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